5 import FWCore.ParameterSet.Config
as cms
9 def __init__(self,cfgFile,html,quiet,helperDir,fullDir):
16 self.
_reg = re.compile(
"['>]")
22 "DictParent":{
"creator":
"dictCreate",
"simple":
True},
23 "ModuleSeqParent":{
"creator":
"modSeqCreate",
"simple":
False},
24 "ProdConsumParent":{
"creator":
"prodConCreate",
"simple":
False}
26 for name,x
in self._parents.iteritems():
29 self.
_type =
"%stypes.js"%(fullDir)
31 self.
_config = ConfigDataAccessor.ConfigDataAccessor()
32 self._config.open(cfgFile)
37 topObjs = self._config.topLevelObjects()
41 with open(self.
_type,
'w')
as f:
42 f.write(
"var %s=%s"%(ty,genericTypes))
47 fN = fileName.split(
"./")[-1].
split(
".")[0]
50 self._config.process().name_(), fN)
54 print "---Nothing found for file %s."\
55 " No computation done.---"%(fileName)
62 name = self._config.label(each)
63 kids = self._config.children(each)
65 if(
not self.
_quiet):
print name,
"is empty."
69 if(ty
is ConfigDataAccessor.ConfigFolder):
72 if(
not self.
_quiet):
print "computing %s.."%(name)
73 if(isinstance(kids[0], seq._ModuleSequenceType)):
81 if(self.
_quiet):
print "calculated: %s."%(
", ".
join(calc))
88 json = [topLevel,theDataFile]
89 cap = namep.capitalize()
92 with open(fullDataFile,
'w')
as data:
100 name = self._config.label(item)
103 key = self._config.label(item)
106 self._config.fullFilename(item), self._config.type(item),
"")
108 with open(fullTopLevel,
'w')
as other:
113 gen, spec = re.sub(self.
_reg,
"",
114 str(item.__class__)).
split(
".")[-2:]
120 mo =self._config.motherRelations(item)
121 dau = self._config.daughterRelations(item)
123 self._mother[name] = [self._config.label(i)
for i
in mo]
125 self.
_daughter[name] = [self._config.label(i)
for i
in dau]
130 always= types =
False
134 if(globalType ==
"modules"):
138 always = types =
True
140 if(always
or not types):
146 name = self._config.label(item)
148 if(isinstance(item,cms._Parameterizable)):
150 elif(isinstance(item,cms._ValidatingListBase)):
152 if(isinstance(item,cms._TypedParameterizable)):
157 self._config.fullFilename(item),
158 self._config.type(item), oType)
159 with open(fullDataFile,
'w')
as dataFile:
168 if(option): basicName = option%(name)
169 else: basicName =
"%s.js"%(name)
170 return (basicName,
"%s%s"%(self.
_theDir,basicName))
176 for name,theDict
in {
"producer":self._mother,
182 with open(fulldataFile,
'w')
as moth:
185 jsonfiles =
" ".
join([
"%s%s"%(self.
_helperDir,x)
for x
in jsonfiles])
187 temp[
"data-base"] = base
188 temp[
"data-files"] = jsonfiles
189 self._data[name] = temp
194 base =
"obj= Object.create(new %s(%s));"
203 for pname,x
in self._parents.iteritems():
204 simple = base%(pname,name)
205 filename,fullfilename= x[
"cfile"]
206 self._allJSFiles.append(filename)
209 with open(fullfilename,
'w')
as setUp:
210 setUp.write(format%(x[
"creator"],paramName,self.
_load(
211 name,paramName,simple)))
214 paramName=[
"modules",
"topLevel"]
215 complexOne = base%(pname,
"%s,%s"%(name, secName))
216 with open(fullfilename,
'w')
as setUp:
217 setUp.write(format%(x[
"creator"],
", ".
join(paramName),
218 self.
_load(name,paramName[0],
219 self.
_load(secName, paramName[1],complexOne))))
224 loadJSON(%s).done(function(%s){\n%s\n});
225 """%(param,name,inner)
229 exVar =
'this.%(key)sKey= "%(key)s";'
233 * @param {String} the key to the dictionary.
234 * @returns {String || Integer} result from dictionary if found else 0.
236 %(name)s.prototype.get%(key)s = function(key){
237 return this.getFeature(key,this.%(key)sKey);
240 search =
"""%(name)s.prototype.search%(key)s = function(reg,term,replce){
241 return this.generalSearch(reg,term,replce,this.%(key)sKey);
246 * Uses the list of parents names to go further into
247 * the lists in the dictionry, and give the last parents children.
248 * @param {Array} the names of parents to look through.
249 * First parent should be a key to the dictionary.
250 * @param {Integer} the index where the elusive parameter is. Needed incase
251 * we have a list with muultiple parameters of the same name.
253 * @returns {Array} the resulting children from the last parent.
255 DictParent.prototype.getInnerParams = function(parents, index){
256 var currentList = this.data[parents[0]][this.%(key)sKey];
258 var siblingsOfTarget=[]
259 for(var i=1; i < parents.length;i++){
260 for(var p=0; p < currentList.length;p++){
261 if(currentList[p][0]==parents[i]){
262 targetList = currentList[p]
263 siblingsOfTarget=currentList
264 var found = targetList[1];
270 if(p != index)targetList=siblingsOfTarget[index]
278 fileName, fullfileName= data[
"pfile"]
279 for feature
in dictFeatures:
280 d = {
"key": feature,
"name": name}
283 if(feature ==
"Parameters"):
287 self._allJSFiles.append(fileName)
288 with open(fullfileName,
'w')
as parent:
291 Base Object for dictionaries.
292 To use, create a dictParent obj,
293 then use Object.create to create a new obj
294 then you can change some variables/add functions
295 and have the inherited functions.
297 function %(name)s(data){
302 * Finds the desired feature from a dictionary.
303 * @param {String} the key to the dictionary.
304 * @param {String} the feature we want from the dictionary.
305 * @returns {String || Integer} result from dictionary if found else 0.
307 %(name)s.prototype.getFeature = function(key, feature){
308 var temp = this.data[key];
309 if(temp) return temp[feature];
312 DictParent.prototype.getData = function(){
318 * Gives the keys from desired dictionary.
319 * @returns {Array} all keys from the dictionary.
321 %(name)s.prototype.getKeys = function(){
322 return Object.keys(this.data);
324 %(name)s.prototype.generalSearch = function(reg,term,repl,feature, d){
328 var x= d[key][feature]
329 if(x.indexOf(term)>-1){
330 matches[key] = x.replace(reg,repl)
337 * Gives the generic type for a given type.
338 * @param {String} type
339 * @returns {String} the generic type
341 function getGenericType(type){
342 return %(gen)s[type];
344 """%{
"theVars":variables,
"getterFunctions":functs,
345 "gen": typeName,
"name":name})
351 * Gives the direct children
352 * @param {String} a path name
353 * @returns {Array} list of names of the the children.
355 %(name)s.prototype.getModules = function(name){
356 return this.topLevelData[name][this.ParametersKey];
358 %(name)s.prototype.getTopFile = function(key){
359 return this.topLevelData[key][this.FileKey];
361 %(name)s.prototype.getData = function(){
362 return [this.topLevelData, this.data];
364 %(name)s.prototype.searchType = function(reg,term,replce){
365 return this.generalSearch(reg,term,replce,this.TypeKey, this.topLevelData);
367 %(name)s.prototype.searchFile = function(reg,term,replce){
368 return this.generalSearch(reg,term,replce,this.FileKey, this.topLevelData);
377 * Gives the direct children
378 * @param {String} a path name
379 * @returns {Array} list of names of the the children.
381 %(name)s.prototype.getModules = function(name){
382 return this.topLevelData[name];
384 %(name)s.prototype.getTopFile = function(key){
385 return this.getFile(key);
387 %(name)s.prototype.getData = function(){
388 return [this.topLevelData, this.data];
390 // Producer and consumer have different structure to rest.
391 // Dont have file and type with them..
392 // to get file and type we need to take each name,
393 //look up the moduledata and find matches.
394 %(name)s.prototype.generalSearch = function(reg,term,repl, feature){
396 for (var key in this.topLevelData){
397 var x = this.data[key][feature]
398 if(x.indexOf(term)>-1){
399 matches[key] = x.replace(reg,repl)
404 %(name)s.prototype.typeSearch = function(reg,term,replce){
405 return this.generalSearch(reg,term,replce,this.TypeKey);
407 %(name)s.prototype.fileSearch = function(reg,term,replce){
408 return this.generalSearch(reg,term,replce,this.FileKey);
416 fileName, fullfilename= data[
"pfile"]
417 self._allJSFiles.append(fileName)
420 Base object for thing of the type:
421 It also inherits from DictParent.
423 function %(name)s(data,topLevel, nameList,indexList){
425 this.topLevelData=topLevel;// e.g. pathNames to module names
426 this.fixedNameList = nameList; // e.g.names of paths
428 %(name)s.prototype = new %(dict)s(this.data);
430 %(name)s.prototype.getKeys = function(){
431 return Object.keys(this.topLevelData)
434 with open(fullfilename,
'w')
as parent:
435 parent.write(all%{
"name": name,
"dict": self.
_dictP})
442 for (name,valType)
in parameters.iteritems():
443 theT= (valType.configTypeName()
if(
444 hasattr(valType,
"configTypeName"))
else "").
split(
" ",1)[-1]
445 temp = re.sub(
"<|>|'",
"", str(type(valType)))
446 generic, spec = temp.split(
".")[-2:]
449 if(isinstance(valType,cms._Parameterizable)):
451 elif(isinstance(valType,cms._ValidatingListBase)):
454 if(isinstance(valType,cms._SimpleParameterTypeBase)):
455 value = valType.configValue()
458 value = valType.pythonValue()
461 theList.append(value)
462 if(theT !=
"double" and theT !=
"int" and type(valType)!= str):
463 if(
not valType.isTracked()):
464 theList.append(
"untracked")
475 if(
not VList):
return ""
477 if(isinstance(first,cms._Parameterizable)
or
478 isinstance(first,cms._ValidatingListBase)):
480 if(isinstance(first,cms._ValidatingListBase)):
484 if(member.hasLabel_()):
485 name = member.label()
487 name = member.configTypeName()
489 if(
not anotherVList):
493 temp = re.sub(
"<|>|'",
"", str(type(member)))
494 generic, spec = temp.split(
".")[-2:]
496 innerList.append(spec)
497 outerList.append(innerList)
499 elif(isinstance(first,cms._SimpleParameterTypeBase)):
500 return ",".
join(i.configValue()
for i
in VList)
501 elif(isinstance(first,cms._ParameterTypeBase)):
502 return ",".
join(i.pythonValue()
for i
in VList)
506 outcome =
",".
join(str(i)
for i
in VList)
509 return "Unknown types"
512 dictFeatures=[
"Parameters",
"Type",
"File",
"oType"]
516 d[dictFeatures[0]] = params
517 d[dictFeatures[1]] = typ
518 d[dictFeatures[2]] = fil
519 d[dictFeatures[3]] = oType
547 return re.sub(self.
_reg,
"", str(type(val))).
split(
".")[-2:]
550 Do Module Objects e.g. producers etc
552 def _doModules(self,modObj, dataFile, seq, seqs, currentName, innerSeq):
554 name = self.config.label(modObj)
557 self._underPath.append(name)
559 seqs[currentName].
append([name])
562 if(name
not in self._modulesToPaths.keys()):
564 filename = modObj._filename.split(
"/")[-1]
565 generic,specific = self.
_getType(modObj)
568 filename, specific, modObj.type_())
570 if(len(self._modulesToPaths.keys()) > 1): theS=
","+theS
577 if(isinstance(value,cms._Module)):
580 elif(isinstance(value,cms._Sequenceable)):
581 generic,specific = self.
_getType(value)
583 if(isinstance(value, cms._ModuleSequenceType)):
586 name = self.config.label(value)
593 self._underPath.append(name)
594 self.
_seqs[name] = []
599 name = value.__str__()
603 self._underPath.append(value.__str__())
606 self._df.write(
',"%s":%s'%(name,
JSONFormat(d)))
607 self._done.append(name)
610 if(isinstance(value,cms._Module)):
612 elif(isinstance(value,cms._Sequenceable)):
615 if(isinstance(value, cms._ModuleSequenceType)):
617 name = self.config.label(value)
618 if(name
in self.
_oldNames):self._oldNames.remove(name)
625 generic,specific = self.
_getType(value)
627 self._df.write(
',"%s":%s'%(name,
JSONFormat(d)))
628 self._done.append(name)
633 def __init__(self,name,js,items,theDir, helperDir, pN,pFN):
634 jqName =
"%scfgJS.js"%(theDir)
635 jqLocal =
"%scfgJS.js"%(helperDir)
636 css =
"%sstyle.css"%(theDir)
637 cssL =
"%sstyle.css"%(helperDir)
645 <script type="text/javascript" src="%s"></script>"""
646 return "\n".
join([x%(i)
for i
in js])
650 <option value=%(n)s data-base="%(d)s" data-files="%(f)s"> %(n)s</option>"""
651 s= [l%({
"n":x,
"f":y[
"data-files"],
"d":y[
"data-base"]})
652 for x,y
in items.iteritems()]
656 b =
"""<option value="%(name)s" data-base="%(d)s">%(name)s</option> """
657 return "\n ".
join([b%({
"name": x,
"d":y[
"data-base"]})
658 for x,y
in items.iteritems()])
661 with open(name,
'w')
as htmlFile:
662 htmlFile.write(
"""<!DOCTYPE html>\n<html>\n <head>
663 <meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
664 <title>cfg-browser</title>\n <script type="text/javascript"
665 src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
666 </script>\n %(s)s\n %(css)s\n </head>\n <body>
667 <div class="topBox topSpec">
668 <input type="submit" value="Edit" id="editMode" autocomplete="off"
669 disabled/>\n <div class="helpLinks">
670 <a href="#" class="nowhere" id="helpMouse" data-help="#help">help
672 <a href="mailto:susie.murphy@cern.ch?Subject=CfgBrowserhelp"
673 target="_top">Contact</a>\n </div>\n <div id="help"> </div>
674 <span id="mode">Normal Mode</span>
675 <div class="topBox hideTopBox">hide</div>\n </div>
676 <a id="topOfPage"></a>\n <br/><br/><br/>\n <div class="outerBox">
677 <div class="boxTitle"> Pick\n <div class="dottedBorder">
678 <form onsubmit="return false;">\n <select id="showType">
679 %(items)s\n </select>\n <br/><br/>
680 <input type="submit" id="docSubmit" value="submit">
681 </form>\n </div>\n </div>
682 <div class="boxTitle"> Pick\n <div class="dottedBorder">
683 <form onsubmit="return false;">
684 <input type="text" id="searchWord"/>
685 <select id="searchType">\n %(search)s
686 </select> \n <span id="addSearch"> </span>
688 <input type="submit" value="Search" id="search"/>
689 <input type="checkbox" id="rmHilight" value="File"/>
690 <span>Don't show highlights</span>\n </form>
691 </div>\n </div>\n </div> \n <br/>
692 <input type="checkbox" id="ShowFiles" value="File"/>
693 <span>Show file names</span>\n <br/><br/>\n <script>
694 document.getElementById("searchType").selectedIndex = -1;\n </script>
695 <div id="posty"> </div>\n <br/>\n <div id="current"></div>
696 <br/>\n <div id="searchCount"></div>\n <div id="attachParams"></div>
697 <div class="rightScroll">\n <a href="#topOfPage">Back to Top</a>
698 <p>\n <a id="hide" href="javascript:;" >Hide All</a>\n </p>
699 </div>\n </body>\n</html>\n"""%{
700 "s":scrip,
"css":css,
"items":items,
"search":search})
703 with open(css,
'w')
as cssfile:
705 *{\n font-family:"Lucida Grande", Tahoma, Arial, Verdana, sans-serif;\n}
706 .topBox{\n opacity:0.9;\n background-color:#dfdfdf;\n}\n.topSpec{
707 position:fixed;\n top:0;\n left:0;\n width:100%;\n height:2.5em;
708 border-radius:.9em;\n}\n.hideTopBox, .showTopBox{\n position:absolute;
709 top:2.5em;\n right:2%;\n width:auto;\n height:auto;\n padding: 0.2em;
710 font-weight:bold;\n cursor:pointer;\n border-radius:.3em;\n}\n.negative{
711 position:absolute;\n right:0;\n text-decoration:none;
712 font-weight:bold;\n color:#565656;\n}\n#mode{\n position:absolute;
713 right:50%; \n color:#808080;\n font-size:12pt;\n}\n#editMode,#normalMode{
714 position:absolute;\n left:.3em;\n top:.5em;\n}\n#save{
715 position:absolute;\n top:.5em;\n}\n.helpLinks{\n position:absolute;
716 right:1.3em;\n width:6.2em;\n text-align:right;\n}
717 /* divs for the Pick and Search boxes.*/\n.outerBox{\n width:100%;
718 overflow:hidden;\n}\n.boxTitle{\n float:left;\n margin-left:.6em;
719 color:#A9A9A9;\n}\n.dottedBorder{\n width:25em;\n height:4em;
720 border:.1em dashed #A9A9A9;\n padding:.6em;\n}\n/* -- */
721 /* Right scroll box. */\n.rightScroll{\n position:fixed;\n bottom:50%;
722 right:0; \n width:6.2em;\n text-align:right;\n border:.1em solid #A9A9A9;
723 opacity:0.4;\n background-color:#F0FFF0;\n}\n#hide{\n cursor:default;
724 opacity:0.2;\n}\nli{\n padding-left:.8em;\n}\nul{\n list-style-type:none;
725 padding-left:.1em;\n}\n/* Icons before list items. */\n.expand:before{
726 content:'›';\n}\n.expanded:before{\n content:'ˇ';\n}
727 .expand:before,.expanded:before{\n float:left;\n margin-right:.6em;\n}
728 .expand,.expanded{\n cursor:pointer;\n}\n/* colours of each. */
729 .Path,.EndPath{\n color:#192B33;\n}\n.Modules{ \n color:#800080;\n}
730 .SequenceTypes{\n color:#0191C8\n}\n.paramInner,.Types{\n color:#4B4B81;\n}
731 .param{\n color:#9999CC;\n margin-left:.8em;\n cursor:default; \n}\n.value{
732 color:#0000FF;\n}\n.type{\n color:#00CCFF;\n}
733 /* Header for what's showing */\n#current{\n color:#808080;\n font-size:12pt;
734 text-decoration:underline; \n}\n/* help settings */\n#help{
735 position:absolute;\n display:none;\n background:#ccc;\n border:.1em solid;
736 width:19em;\n right:15em;\n top:1.2em;\n}\nh5{\n font-style:normal;
737 text-decoration:underline; \n margin:0;\n font-size:9pt;\n}\nh6{
738 margin:0;\n color:#666666;\n}\n#attachParams{\n color:#192B33;\n}\nem{
739 color:#FFA500;\n}\n.cellEdit{\n border:.1em dotted #A9A9A9;\n cursor: text;
741 return """<link href="%s" rel="stylesheet" \
742 type="text/css"/>"""%(cssLocal)
745 with open(name,
'w')
as jq:
747 \n$(document).ready(function(){ \n//Object used to get all details
748 var processName="%s";\nvar processFileName ="%s";
749 var CURRENT_OBJ;\nvar searchShowing= false;\nvar showParams = false
750 var alreadyShowing = false\nvar topClass = "Top"\nvar searching = false
751 var expandDisable = false;\nvar hideVisible=false //nothing is expanded.
752 // ---\n/*\n Functions used to abstract away name of function calls
753 on the object (CURRENT_OBJ).
754 (i.e. so function names can easily be changed.)\n*/
755 function baseParams(inputs){\n return CURRENT_OBJ.getParameters(inputs);\n}
756 function baseInnerParams(inputs, index){
757 return CURRENT_OBJ.getInnerParams(inputs, index);\n}
758 function baseType(inputs){\n return CURRENT_OBJ.getType(inputs);\n}
759 function baseFile(inputs){\n return CURRENT_OBJ.getFile(inputs);\n}
760 function baseTopFile(inputs){\n return CURRENT_OBJ.getTopFile(inputs);\n}
761 // --- Show some inital data operations ---\n/*\n Show something new!\n*/
762 $(document).on('click', '#docSubmit', function(e){
763 var $elem = $('#showType :selected')
764 //get the function we want and the lists\n setCURRENT_OBJ($elem)\n
765 addData($elem.attr("value"), CURRENT_OBJ.getKeys());\n searchShowing= false;
766 });\n/*\n Add data to the html.\n*/
767 function addData(docType, data, dataNames){
768 $("#editMode").removeAttr("disabled"); \n var dataNames = dataNames || data;
769 if(alreadyShowing){\n //need to click cancel if its active.
770 goNormal($("#normalMode"));\n if(!searching)$("#searchCount").html("")
771 invisibleHide()\n paramOptions(false)
772 $(document.getElementsByTagName('body')).children('ul').remove();\n }
773 $("#current").html(docType)\n var gen = getGenericType(docType)
774 var ty = docType\n if(gen != undefined){\n var gL = gen.toLowerCase()
775 if(gL=="modules"||gL=="types") var ty= gen;\n }
776 var $LI = $(document.createElement('li')
777 ).addClass("expand").addClass(ty).addClass(topClass);
778 docType= docType.toLowerCase()\n var showTypes = false\n showParams = true
779 switch(docType){\n case "producer":\n case "consumer":
780 showParams = false\n paramOptions(true)
781 $LI.addClass("Modules")\n showTypes = true\n break;
782 case "modules":\n $LI.addClass("Modules")\n showTypes = true
783 //showParams = true\n break;\n }
784 var $UL = addTopData(data,$LI,showTypes,dataNames)\n alreadyShowing = true;
785 $UL.appendTo('#attachParams');\n}\n/*
786 Used to add the top level data to html.\n*/
787 function addTopData(data,$LI,types,dataName){
788 var dataName = dataName || data;
789 var $UL = $(document.createElement('ul'));\n var doNormalFile = false;
790 var files = document.getElementById("ShowFiles").checked\n if(files){
791 try{\n baseTopFile(dataName[0])\n }\n catch(e){
792 doNormalFile = true;\n }\n }\n for(var i=0; i < data.length;i++){
793 var n = dataName[i]\n var t = data[i];
794 if(types)t += " ("+baseType(n)+")"\n if(files){
795 if(doNormalFile)var file = baseFile(n)
796 else var file = baseTopFile(n)\n t += " ("+file+")"}
797 $UL.append($LI.clone().attr("data-name",n).html(t));\n }\n return $UL;\n}
798 // --- end of inital showing data operations ---\n
799 // --- search operations ---\n
800 //$(document).on('click', "[name='searchTerm1']", function(e){
801 //$(document).on('click', "#searchType option", function(e){
802 $(document).on('click', '#searchType', function(e){\n $("#addSearch").empty()
803 var tname= $(this).text().toLowerCase();\n var sel= jQuery('<select/>', {
804 id:"searchType2"\n })
805 var li = (tname =="modules"|| tname == "producer"|| tname == "consumer")?
806 ["Name", "Type", "File"]: ["Name", "File"]\n for(var i in li){
807 var x = li[i]\n jQuery('<option/>',{\n value:x,\n text:x
808 }).appendTo(sel)\n }\n sel.appendTo("#addSearch");\n});\n/*
809 Current search only searches for top level things.\n*/
810 $(document).on('click','#search', function(e){\n searching = true
811 var first = $('#searchType :selected')\n if(first.length ==0){
812 window.alert("Please chose a search type."); \n return;\n }
813 var doc = first.text()\n var searchTerm = $('#searchWord').val()
814 var $elem = $('option[value="'+doc+'"]')\n setCURRENT_OBJ($elem)
815 var reg = new RegExp(searchTerm, 'g')
816 if($('#rmHilight').prop('checked'))\n var fin = searchTerm\n else
817 var fin = "<em>"+searchTerm+"</em>"
818 switch($('#searchType2 :selected').text()){\n case "File":
819 $("#ShowFiles").prop('checked', true);
820 var items = CURRENT_OBJ.searchFile(reg,searchTerm,fin)
821 var matchCount = fileTypeSearch(doc,items,true)\n break;
822 case "Type":\n var items = CURRENT_OBJ.searchType(reg,searchTerm,fin)
823 var matchCount = fileTypeSearch(doc,items,false)\n break
824 case "Name":\n var matchCount = easySearch(searchTerm,reg, doc, fin)
825 }\n $("#searchCount").html(matchCount+ " found.")\n searching = false;
826 searchShowing= true;\n});\n/*\n Used when searching top level elements.
827 i.e. Module names, path names etc.
828 We dont need to delve into any dictionaries, we just use the keys.\n*/
829 function easySearch(term,reg, doc, fin){\n var keys = CURRENT_OBJ.getKeys()
830 var matches = keys.filter(function(e, i, a){return (e.indexOf(term)>-1)})
831 var highlights = matches.map(function(e,i,a){
832 return e.replace(reg, fin)})
833 addData(doc, highlights,matches)\n return matches.length\n}\n/*
834 When searching type or file names of top level elements.\n*/
835 function fileTypeSearch(doc,items,file){
836 var newFunct = function(name){return items[name]}\n if(file){
837 var backup = baseFile\n var backup2 = baseTopFile
838 baseFile = newFunct \n baseTopFile = newFunct\n }\n else {
839 var backup = baseType\n baseType = newFunct\n }
840 var matches = Object.keys(items)\n addData(doc, matches)\n if(file){
841 baseFile = backup\n baseTopFile = backup2\n }\n else baseType = backup
842 return matches.length\n}\n// --- end of search operations ---\n
843 // --- edit operations ---\n// variables needed:
844 // will contain the highest parents, where something *might*
845 // be changed in its children.\nvar $potential=[]
846 // dict, keys are parentNames and values are lists of children changed
847 // under that parent\nvar parChildNames={}\n
848 $(document).on('click', '#editMode', function(e){\n if(searchShowing)
849 var dataType = $('#searchType :selected').attr("data-base")
850 else var dataType = $('#showType :selected').attr("data-base")
851 // Temp restriction of editing SequenceTypes e.g. Paths,EndPaths etc.
852 if(dataType=="modSeqCreate"){
853 window.alert("At the moment editing for SequenceTypes"+
854 " has been disabled.");\n return;\n }
855 else if (dataType == "prodConCreate"){
856 window.alert("Sorry, it is currently not possible to "+
857 "edit producers and consumers.");\n return;\n }
858 if(CURRENT_OBJ == undefined)return;
859 // this is editing mode, turn off expansion\n expandDisable = true;
860 $("#mode")[0].textContent = "Edit Mode"\n $(this).attr("value", "Cancel");
861 var l = ($(this).width()/ parseFloat($("body").css("font-size"))+2.5)+"em"
862 $(this).after(jQuery('<input>', {\n type:"submit",
863 value:"Save",\n id:"save"\n }).css({\n left:l\n}));
864 $(this).attr("id", "normalMode")\n makeEditable(searchShowing);
865 searchShowing = false;\n});\n/*
866 Adds in div elements to make cells editable.\n*/
867 function makeEditable(rmSearch){\n // add editable div to everything showing.
868 var todo = jQuery.makeArray($(".Top"));\n while(todo.length){
869 var e = $(todo.pop())\n if(rmSearch)
870 e.html(e.html().replace(/(<em>|<\/em>)/g, ""))
871 // we have the item.. lets get children
872 var kids = jQuery.makeArray(e.children());
873 // add divs to all children.\n while(kids.length){
874 var k = $(kids.pop())\n var tag = k.prop("tagName")\n
875 if(tag == "SPAN"){\n if(k.prop("class")!="type")
876 k.html('<div class="cellEdit" contenteditable>'+k.html()+'</div>')
877 continue\n }\n if(tag =="LI"){
878 // add the div but dont get children
879 $(k.contents()[0]).wrap('<div class="cellEdit" contenteditable />');
880 }\n // check if have any children
881 var moreKids = jQuery.makeArray(k.children());
882 if(moreKids.length){\n kids = kids.concat(moreKids)\n }
883 }\n // now do current one
884 $(e.contents()[0]).wrap('<div class="cellEdit" contenteditable />');\n }
885 }\n/*\n A cell which is editable has been clicked.\n*/
886 $(document).on('click', '.cellEdit', function(e){
887 // we're in edit so things have a div parent over the text.
888 // so get parent to get the thing we want.
889 var $itemChanged = $(this).parent()
890 // now go up until we find greatest parent(item with class==topClass)
891 var classes = $itemChanged.attr("class")\n var $parent = $itemChanged
892 while(classes.indexOf(topClass)==-1){\n $parent = $parent.parent();
893 classes = $parent.attr("class") || "";\n }
894 var parentName = $parent.attr("data-name");
895 // doesnt matter if parent and child are the same.
896 var parents = Object.keys(parChildNames)
897 if(parents.indexOf(parentName)>-1){\n // already been edited.
898 var kids = parChildNames[parentName]
899 if(kids.indexOf($itemChanged.attr("data-name"))==-1){
900 kids.push($itemChanged)\n }\n }\n else{
901 parChildNames[parentName]=[$itemChanged]\n }\n $potential.push($parent)
902 });\n//--- end of edit operations ---\n// --- start of save operations ---\n/*
903 Save any changes.\n*/\n$(document).on('click', '#save', function(e){
904 var allData = CURRENT_OBJ.getData();\n var oldData = allData[0]
905 goNormal($("#normalMode"));\n if(allData.length >1){
906 var top = allData[0];\n var rest = allData[1];
907 var changed = save(deepCopy(top),deepCopy(rest))\n }\n else{
908 var changed = save(deepCopy(allData[0]));\n }
909 if(Object.keys(changed).length ==0){
910 window.alert("Nothing was changed.");\n $potential=[]
911 parChildNames={}\n return \n }
912 //$('#svg_export_form > input[name=svg]').val("jhgjhg");
913 changed["processName"]= processName
914 changed["processFileName"]= processFileName\n $("#posty").empty()
915 var form = jQuery('<form/>', {\n id:"edited_write",\n method:"POST",
916 async: "false",\n enctype: "multipart/form-data",
917 style:"display:none;visibility:hidden",\n })\n jQuery('<input/>', {
918 type:"hidden",\n name:"changed",\n value:JSON.stringify(changed),
919 }).appendTo(form)\n form.appendTo("#posty")\n $('#edited_write').submit();
920 $potential=[]\n parChildNames={}\n});\n/*
921 Go to normal viewing mode. Discard any changes.\n*/
922 $(document).on('click', '#normalMode', function(e){
923 //remove all cell edit Divs\n goNormal($(this));\n //$potential =[]
924 //parChildNames={}\n});\n/*\n Couldn't find built-in deep clone or copy.\n*/
925 function deepCopy(obj){\n if(obj instanceof Array){\n var copy=[]
926 obj.forEach(function(x,i,a){copy[i]= deepCopy(x)})\n return copy\n }
927 else if(obj instanceof Object){\n var copy ={}\n for (key in obj){
928 copy[key] = deepCopy(obj[key])\n }\n return copy\n }\n return obj
929 }\n\n/*\n Returns a dict of everything that has changed.\n*/
930 function save(data, restData){\n var allChanged={}\n var done=[]
931 for(var i in $potential){\n var parent = $potential[i];
932 // we have the parent.
933 var oldParentName = $(parent).attr("data-name");
934 //bit iffy, can have same parent name multiple times? todo
935 if(done.indexOf(oldParentName)>-1) continue\n done.push(oldParentName)
936 if(typeof restData =='undefined'){
937 var allDict = deepCopy(data[oldParentName])
938 var allOldData = allDict["Parameters"]
939 var childChanged = parChildNames[oldParentName]
940 var oldToNew= chil(childChanged,parent, true)
941 if(oldToNew.length ==0) continue
942 var newpar = blah(oldToNew, oldParentName, allOldData, parent, false)
943 tempDict = allDict\n tempDict["Parameters"] = allOldData
944 allChanged[newpar] = tempDict\n if(oldToNew.length>0){
945 window.alert("Something went wrong, I did not find all changes.");
947 // we have one data for the parents and one for rest
948 var allDict = deepCopy(data[oldParentName])
949 var allKids = allDict["Parameters"]\n var tem ={}
950 var childChanged = parChildNames[oldParentName];
951 var oldToNew = chil(childChanged,parent, false);
952 //if(Object.keys(oldToNew).length ==0) continue
953 if(oldToNew.length ==0) continue\n for (var y in allKids){
954 var n = allKids[y]\n var allOld2 = deepCopy(restData[n])
955 var allOldData = allOld2["Parameters"]
956 // blah chanhes allOldData
957 var newpar = blah(oldToNew, n, allOldData, parent, true)
958 allOld2["Parameters"]= allOldData\n tem[newpar] = allOld2
959 }\n var newParentName = $(parent).contents()[0].nodeValue
960 //allChanged[newParentName]= tem\n tempDict = allDict
961 tempDict["Parameters"] = tem\n allChanged[newParentName] = tempDict
962 continue\n }\n }\n return allChanged\n}\n/*
963 These three functions are used for getting data from
964 a structure such as [{},{},{}]\n*/\nfunction getValue(list, key){\n var re=[]
965 for(x in list){\n di = list[x]\n k = Object.keys(di)[0]
966 if(k==key)re.push(di[k])\n }\n return re\n}\nfunction getKeys(list){
967 var keys = []\n for (x in list)\n keys.push(Object.keys(list[x])[0])
968 return keys\n}\nfunction deleteValue(list, k,d){\n var inde =-1
969 var found = false\n for(var x in list){\n var di = list[x]
970 var key = Object.keys(di)[0]\n if(key==k && di[key]==d){
971 found = true\n inde = x\n break\n }\n }
972 if(found)list.splice(inde,1)\n}\n/*
973 allOldData will be changed with the new data.\n*/
974 function blah(oldToNew, oldParentName, allOldData, parent){
975 var newpar = oldParentName\n var keys = getKeys(oldToNew)
976 if(keys.indexOf(oldParentName)>-1){\n // parent is in
977 var tDatas = getValue(oldToNew,oldParentName);
978 for (var x in tDatas){\n var tData = tDatas[x]
979 if(tData["i"]==0 && tData["p"].length ==0){
980 var newpar = tData["new"];\n // this isnt finding tData
981 deleteValue(oldToNew, oldParentName,tData);\n }\n }\n }
982 // okay so here we have everything for this parent.
983 // now need to loop through the old data and changed for new.
984 if(oldToNew.length >0){
985 loopData(allOldData,oldToNew,[oldParentName], [0]);\n }
986 return newpar\n}\n//need to remember that current format is
987 //[name, parameters,type,optionalType]\n/*\n Loop around the data, \n*/
988 function loopData(thelist, items, parents, pIndex){\n for(var x in thelist){
989 var y = thelist[x]\n if(y instanceof Array){
990 // okay if array, we have full line
991 if(typeof y[0] == "string" && y[1] instanceof Array){
992 // this is what we want.\n var theName = y[0]
993 var rest = y[1]\n var types = [y[2]]\n if(y.length == 4)
994 types.push(y[3])\n // okay, name of this is theName == parent
995 // the index of this is x\n parents.unshift(theName)
996 pIndex.unshift(x)\n loopData(rest, items, parents, pIndex);
997 parents.shift()\n pIndex.shift()
998 rightOne(thelist,x,theName,items,parents,pIndex)
999 for(var index in types){\n var item = types[index]
1000 rightOne(thelist,x,item,items,parents,pIndex)\n }
1002 if(y[0] instanceof Array && y[1] instanceof Array){
1003 // y1 is a parameter\n // y2 is a parameter
1004 for(var e in y){\n loopData(y[e],items,parents,pIndex);
1005 }\n continue;\n }\n // we are here,
1006 //so we have something that does not have parameters in a list
1007 var theName = y[0]\n for(var index in y){\n if(index >0){
1008 parents.unshift(theName) \n pIndex.unshift(x)\n }
1010 rightOne(thelist,x,item,items,parents,pIndex)\n if(index >0){
1011 parents.shift()\n pIndex.shift()\n }\n }
1012 continue;\n }\n else {
1013 rightOne(thelist,x,y,items,parents,pIndex)\n }\n }\n}\n/*
1014 Helper function. We have a match, now change old values for new values.\n*/
1015 function rightOne(thelist,x,y,items,parents,pIndex){
1016 if(getKeys(items).indexOf(y)>-1){
1017 // we know that we have a match, but are indexes the same?
1018 // index will be in the same list so we can use x
1019 var dis = getValue(items, y)\n for (inde in dis){
1020 var di= dis[inde]\n if(x == di["i"]){
1021 if(arrayCompare(parents, pIndex,di["p"],di["pIndex"] )){
1022 //okay we can be sure we are changing the right thing.
1023 if(thelist[x] instanceof Array){
1024 for(var ind in thelist[x]){\n var z = thelist[x][ind]
1025 if(y == z){\n thelist[x][ind] = di["new"]
1027 else{\n thelist[x] = di["new"]\n }
1028 deleteValue(items,y,di)\n }\n }\n }\n }\n}\n/*
1029 Returns true if arrays a1 is identical to a2 and
1030 a1Index is identical to a2Index.\n*/
1031 function arrayCompare(a1, a1Index, a2, a2Index) {
1032 if (a1.length != a2.length)return false;
1033 for (var i = 0; i < a1.length; i++) {
1034 if (a1[i] != a2[i] || a1Index[i] != a2Index[i]) {
1035 return false;\n }\n }\n return true;\n}\n/*
1036 Take in the children that might have been changed.
1037 If something has been changed, adds to a dictionary
1038 dictionary format is [data-name]={
1039 "new": newvalue, "i":data-index, "p":[parentNames],
1040 "pIndex": [indicies of parents]}
1041 TODO, need a new format, what if children have
1042 the same data-name and both are changed?\n*/
1043 function chil (childChanged, parent, addParent){\n var oldToNew=[]
1044 for (var x in childChanged){\n var child = childChanged[x]
1045 // we need to check if the child has been changed.
1046 var oldval = child.attr("data-name");
1047 var isSpan = child.prop("tagName") == "SPAN"\n var newval = isSpan ?
1048 child.contents().text(): child.contents()[0].nodeValue;
1049 //remove any enclosing brackets
1050 newval = newval.trim().replace(/\(.*\)$/, "");
1051 oldval = oldval.trim().replace(/\(.*\)$/, "");
1052 if(oldval==newval)continue\n else{
1053 //child has been changed.\n //we want to keep 4 pieces of data.
1054 //1. old name, new name\n //2. data-index
1055 //3. list of direct parents.\n //4. indexes of all parents.
1056 var inner ={}\n inner["new"] = newval;
1057 //depends if it was a span or not. Span means we use parents.
1058 inner["i"]= (isSpan? child.parent().attr("data-index"):
1059 child.attr("data-index")) || 0\n var allP = child.parents()
1060 var pNames =[]\n var pIndex =[]
1061 for(var y=0; y < allP.length; y++){\n var p = $(allP[y])
1062 var tag = p.prop("tagName")
1063 if(p.attr("data-name") == parent.attr("data-name")){
1064 if(addParent){\n pNames.push(parent.attr("data-name"))
1065 pIndex.push(parent.attr("data-index") || 0);\n }
1066 break;\n }\n else if(tag == "LI"){
1067 pNames.push(p.attr("data-name"));
1068 pIndex.push(p.attr("data-index") || 0);\n }\n }
1069 inner["p"] = pNames\n inner["pIndex"] = pIndex\n var t={}
1070 t[oldval]= inner\n oldToNew.push(t)\n }
1071 } // end of childchanged loop\n return oldToNew\n}
1072 // --- end of save operations ---
1073 // --- Expand and show more data operations ---\n/*
1074 Used when in edit mode to stop any items being added to the webpage.
1075 More items added after edit mode- they wont be editable, and when you
1076 click to edit something it loads its children.\n*/
1077 $(document).on('click','.expand, .expanded', function(event){
1078 if(expandDisable){\n event.stopImmediatePropagation();\n }\n});\n/*
1079 Retrieves and expands elements whose objects have multiple lists
1080 (i.e. onese who's data-base !=simpleData)\n*/
1081 $(document).on('click', '.Consumer.expand,.Producer.expand,'
1082 +'.Path.expand,.EndPath.expand ',function(event){
1083 var allModules = CURRENT_OBJ.getModules($(this).attr('data-name'));
1084 var UL = addParams(this,allModules)\n $(this).append(UL);
1085 event.stopPropagation();\n});\n/*\n Adds parameters onto objects.\n*/
1086 $(document).on('click','.Modules.expand,.SequenceTypes,.Types.expand'
1087 , function(event){\n if(showParams){\n addParams(this);\n }
1088 event.stopPropagation();\n});\n/*\n Hides/Shows children from class param.
1089 */ \n$(document).on('click', '.paramInner.expand, .paramInner.expanded',
1090 function(event){\n if($(this).children('ul').length ==0){
1091 // find parents\n var parents = findParents(this)
1092 var result = baseInnerParams(parents,parseInt(
1093 $(this).attr("data-index")) )[1]
1094 addParams(this, result);\n }\n else{
1095 //children already added, so just hide/show.
1096 $(this).children('ul').toggle();\n }\n event.stopPropagation();
1097 });\n/*\n Find the parents of a child.\n*/\nfunction findParents(child){
1098 var parents =[$(child).attr("data-name")]
1099 var theParent = $(child).attr("data-parent")
1100 while(theParent !=undefined){ \n var child = $(child).parent();
1101 if(child.prop("tagName")=="UL") continue;
1102 parents.unshift(child.attr("data-name"));
1103 theParent = child.attr("data-parent");\n }\n return parents\n}\n/*
1104 Helper function: returns filename appended onto val.\n*/
1105 function getFile(theName){\n var f = baseFile(theName)
1106 if(f)return theName+=type(f)\n return theName\n}\n/*
1107 Add params to the object. Object can be of any type
1108 (normally module or param).
1109 Will be used by modules adding parameters, psets adding parameters.\n*/
1110 var $LIBasic = $(document.createElement('li')).attr("class","param");
1111 var $LIExpand = $LIBasic.clone().attr("class","expand");\n
1112 function addParams(obj, params){
1113 var fileChecked = document.getElementById("ShowFiles").checked
1114 var $span = $(document.createElement("span"));
1115 var $typeSpan = $span.clone().addClass("type");
1116 var $valSpan = $span.clone().addClass("value");
1117 var $UL = $(document.createElement("ul"));
1118 var $objName = $(obj).attr('data-name');\n\n if(!params)
1119 params = baseParams($objName)\n for(var i =0; i < params.length; i++){
1120 var all = params[i].slice() // make copy of it
1121 var isList= typeof(all)=="object"
1122 var theName = isList ? all.shift(): all
1123 var typ= !isList || !all.length ? baseType(theName): all.pop()
1124 var gen = getGenericType(typ)
1125 var spt = $typeSpan.clone().attr("data-name",typ).text(type(typ))
1126 if(fileChecked) text = getFile(theName)
1127 if(isList && typeof(all[0]) == "object"){\n // PSets
1128 var cloLI = doLI(false,theName,i,"paramInner",spt)
1129 cloLI.attr("data-parent", $objName)\n }
1130 else if(baseParams(theName)){\n // Modules or sequences
1131 var cloLI = doLI(false,theName,i,gen,spt)\n }\n else{
1132 // Basic type, has no children\n var cloLI= doLI(true,theName,i)
1133 var value =""\n if(all.length)\n var value = all.shift()
1134 // formating so lots of strings look nicer\n var valDataName = value
1135 if(value.indexOf(",")>-1){
1136 value = "<ul><li>"+value.replace(/,/g, ",</li><li>")+"</li></ul>"
1137 }\n var add = type(typ)
1138 cloLI.append($valSpan.clone().attr("data-name",valDataName).html(value))
1139 cloLI.append($typeSpan.clone().attr("data-name",add).text(add))
1140 for(var p=0; p < all.length; p++){\n var n = type(all[p])
1141 cloLI.append($typeSpan.clone().attr("data-name",n).text(n))\n }
1142 } \n $UL.append(cloLI);\n }\n $(obj).append($UL);\n}\n
1143 function type(theName){\n return " ("+theName+")"\n}\n/*
1144 Helper function: Adds data to a LI.\n*/
1145 function doLI(basic,dataN,dataI,classes,html){
1146 if(basic) var $LI = $LIBasic.clone()\n else var $LI = $LIExpand.clone()
1147 $LI.attr("data-name", dataN).attr("data-index", dataI).text(dataN);
1148 if(classes)$LI.addClass(classes)\n if(html)$LI.append(html)\n return $LI
1149 }\n/*\n Box to show params has been clicked.\n*/
1150 $(document).on('click', '#ShowParams', function(e){
1151 if($(this).is (':checked')){\n showParams = true\n }\n else{
1152 $(this).next().hide()\n showParams = false\n }\n});\n/*
1153 Removes children from top level list elements.\n*/
1154 $(document).on('click', '#hide', function(e){
1155 //make sure not called when not needed.
1156 if($(this).css('cursor')!='default'){
1157 var selec = $(".expanded."+topClass).children("ul").hide()
1158 toggleExpand($(".expanded."+topClass ),e)\n invisibleHide()\n }\n});
1159 // --- end of expand and show more data operations ---
1160 // --- general helper operations and functions ---\n\n/*
1161 Return to normal viewing mode.\n*/\nfunction goNormal(it){
1162 expandDisable = false;
1163 $(".cellEdit").replaceWith(function() { return $(this).contents();});
1164 $("#save").remove()\n $("#mode")[0].textContent = "Normal Mode"
1165 it.attr("value", "Edit");\n it.attr("id", "editMode")\n}\n/*
1166 Set what the CURRENT_OBJ is.\n*/\nfunction setCURRENT_OBJ($element){
1167 var thefunction = $element.attr("data-base");
1168 var list = $element.attr("data-files").split(" ");\n if(list.length >1){
1169 CURRENT_OBJ = window[thefunction](list[1], list[0])\n } \n else{
1170 CURRENT_OBJ = window[thefunction](list[0])\n }\n}\n/*
1171 Add option in html to show/hide parameters.\n*/\nfunction paramOptions(bool){
1172 if(!bool){\n $("#attachParams").empty()\n return\n }
1173 var lb= jQuery('<label/>', {\n for:"ShowParams"\n })
1174 jQuery('<input/>', {\n type:"checkbox",\n id:"ShowParams",
1175 name:"ShowParams",\n value:"ShowParams",\n autocomplete:"off"
1176 }).appendTo(lb)\n lb.append("Show Parameters")
1177 lb.appendTo("#attachParams")\n}\n/*\n Small info about each option.\n*/
1178 $('#showType option').mouseover(function(){
1179 var docType = $(this).attr("value").toLowerCase();\n var info;
1180 switch(docType){\n case "producer":
1181 info="What's produced by each module."\n break;
1182 case "consumer":\n info="What's consumed by each module."
1183 break;\n default:\n info ="List of "+ docType+"s."\n }
1184 $(this).attr("title", info);\n});\n/*\n Small info about each option.\n*/
1185 $('span[name="Info"]').mouseover(function(){
1186 var docType = $(this).attr("value").toLowerCase();\n var info;
1187 switch(docType){\n case "producer":
1188 info="What's produced by each module."\n break;
1189 case "consumer":\n info="What's consumed by each module."
1190 break;\n default:\n info ="List of "+ docType+"s."\n }
1191 $(this).attr("title", info);\n});\n/*\n More info about what's shown.\n*/
1192 $("#helpMouse").hover(function(e) {
1193 $($(this).data("help")).stop().show(100);
1194 var title = "<h6>(Read the README file!)</h6><h4>Info:</h4> "
1195 var expl = "<h5>Colour codes:</h5> <h6><ul><li class='Path'>pathName"+
1196 " </li></ul><ul><li class='Modules'>Modules (e.g. "+
1197 "EDProducer, EDFilter etc)</li></ul><ul><li class='Types'>"+
1198 "Types (e.g. PSet)</li></ul><ul><li class='param'>"+
1199 "ParameterName:<span class='value'> value</span><span"+
1200 " class='type'>(type)</span></li></ul></h6>"
1201 var info ="<h5>The data</h5><h6>The headings you can choose from are"+
1202 " what was collected from the config file.<br/><br/> Any "+
1203 "change to the config file means having to run the script "+
1204 "again and then refresh this page (if same output file was "+
1206 var tSearch="<h5>Search</h5><h6>Currently can only search by listing "+
1207 "what items you would like to be searched, and then what part"+
1208 " of each item.<br/><br/> I.e. search the producers for "+
1209 "certain names.</h6><br/>"
1210 var problems = "<h5>HTML/JSON/JS issues</h5><h6>If content isn't "+
1211 "loading,or json files cannot be loaded due to browser"+
1212 " security issues, try runing the local server created"+
1213 " by the script. This will be in the same place as "+
1214 "index.html.<br/><span class='Types'>'python cfgServer.py'"+
1215 " </span></h6><br/>"
1216 var editing = "<h5>Editing</h5><h6>In order to use the edit mode, you "+
1217 "need to run the cfgServer.py file, this will be in the "+
1218 "same directory as the index.html.<br/>Then go to <span"+
1219 " class='Types'> 'http://localhost:8000/index.html.'"+
1220 "</span><br/><strong>Please note that the editing of "+
1221 "SequenceTypes (i.e. Paths, EndPaths etc) and of producers"+
1222 " and consumers has been "
1223 $($(this).data("help")).html(title+expl+info+problems+editing);
1224 "disabled.</strong></h6><br/>"\n}, function() {
1225 $($(this).data("help")).hide();\n});\n/*
1226 These two functions hide/show the top box in browser.\n*/
1227 $(document).on('click', '.hideTopBox', function(e){
1228 $(".topSpec").animate({top: "-2.5em"}, 500);\n $(this).text("show");
1229 $(this).toggleClass("hideTopBox "+"showTopBox");\n});
1230 $(document).on('click', '.showTopBox', function(e){
1231 $(".topSpec").animate({top: "0em"}, 500);\n $(this).text("hide");
1232 $(this).toggleClass("showTopBox "+ "hideTopBox");\n});\n/*
1233 Stop some links from firing.\n*/\n$('a.nowhere').click(function(e)\n{
1234 e.preventDefault();\n});\n\n// Turn off any action for clicking help.
1235 $('a#help').bind('click', function() {\n return false;\n});\n/*
1236 If parameter value is a list, hide/show the list on click.\n*/
1237 $(document).on('click', '.param',function(event){\n if(!expandDisable){
1238 if($(this).find('ul').length >0){\n $(this).find('ul').toggle();\n }}
1239 event.stopPropagation();\n});\n/*
1240 Removes children from expanded paths or modules.\n*/
1241 $(document).on('click', '.expanded',function(event){
1242 var c = $(this).children('ul');\n if(c.length >0){\n $(c).remove();
1243 }\n event.stopPropagation();\n});\nfunction visibleHide(){
1244 $('#hide').css('opacity',1);\n $('#hide').css('cursor','pointer');
1245 hideVisible = true;\n}\nfunction invisibleHide(){
1246 $('#hide').css('opacity','');\n $('#hide').css('cursor','');
1247 hideVisible = false;\n}\n\n// Toggles class names.
1248 $(document).on('click','.expand, .expanded', function(event){
1249 if(!hideVisible && $(this).is('.expand')){\n visibleHide();\n }
1250 toggleExpand(this, event);\n});\n/*\n Helper function toggles class type.
1251 */\nfunction toggleExpand(me,event){\n $(me).toggleClass("expanded expand");
1252 event.stopPropagation();\n}\n});\n// end of jquery\n/*
1253 Function to load the JSON files.\n*/\nfunction loadJSON(theName){
1254 return $.ajax({\n type: "GET",\n url: theName,
1255 beforeSend: function(xhr){\n if (xhr.overrideMimeType)\n {
1256 xhr.overrideMimeType("application/json");\n }\n },
1257 contentType: "application/json",\n async: false,\n dataType: "json"
1258 });\n} \n"""%(pN,pFN))
1262 genericTypes[spec] = generic
1266 return json.dumps(d)
1273 with open(name,
'w')
as f:
1275 #!/usr/bin/env python\nimport SimpleHTTPServer\nimport SocketServer
1276 import shutil\nimport os\nimport cgi\nimport socket\nimport errno\n
1277 #Right now cannot deal with SequenceTypes\nclass CfgConvert:
1278 def __init__(self, obj):\n self._pName = obj["processName"]
1279 self._pFileN = obj["processFileName"]\n obj.__delitem__("processName")
1280 obj.__delitem__("processFileName")\n self._obj = obj
1282 self.header=\"""import FWCore.ParameterSet.Config as cms
1283 process = cms.Process('%(n)s')\nfrom %(fileN)s import *\n%(changes)s\n\n\"""
1284 def _doConversion(self):\n return self.header%(
1285 {"changes":self._doWork(self._obj),
1286 "n":self._pName,"fileN":self._pFileN})\n\n def _doWork(self, obj):
1287 result =""\n for key, value in obj.iteritems():
1288 _type = value["Type"]\n _file = value["File"]
1289 _params = value["Parameters"]\n _oType = value["oType"]
1290 if(_oType):\n _oType= "'%s',"%(value["oType"])
1291 #f = eval(func%(_type))\n if(type(_params)== list):
1292 if(len(_params)==0):
1293 result +="process.%s= cms.%s(%s)\\n"%(key,_type,_oType[:-1])
1294 else:\n params = self._convert(_params)
1295 result+="process.%s= cms.%s(%s%s)\\n"%(key,_type,_oType, params)
1296 #elif(type(_params)== dict):
1297 # return "Sorry path and endpaths can not currently be translated."
1298 #params = self._doWork(_params)\n
1299 #obj = f("actualType", *parameters)\n return result\n
1300 def _convert(self,params):
1301 # NOTE: params do not take names inside functions
1302 # It is: name = cms.type(value)\n # okay we have a list like
1303 #[name,params, untracked,type]||[name,params,type]
1304 # 2 format options in the params\n # 1. [["name", "value", "type"]]
1305 # 2. [["PsetName",[[as above or this]], "Pset"]]\n
1306 # At position 0 is name. list[0]==name or list[0]==list
1307 # then that will be all
1308 # At position 1 is value or list. list[1]==value||list.
1309 # At position 2 is type. list[2] == type || untracked.
1310 # If there is a position 3 its type. list[3]== type.
1311 if(all(type(x) == list for x in params)):
1312 return ",".join([self._convert(x) for x in params])
1313 length = len(params)\n if(length==1):
1314 if(type(params[0]) == list):\n # wont have params[1]etc
1315 # do inners\n return self._convert(params[0])
1316 #wrong format\n print "Error 01 %s"%(str(params))\n return ""
1317 if(length !=3 and length !=4):\n #wrong format
1318 print "Error 02 len is %s"%(str(params))\n return ""
1319 # okay get on with it.\n name = params[0]
1320 if(type(params[1])==list):\n # do listy things
1321 value = self._convert(params[1])\n else:\n value=params[1]
1322 ty = params[2]\n if(name==ty):\n name=""\n if(length==4):
1323 ty+="."+params[3]\n if(name== params[3]):\n name=""
1324 if("vstring" in ty):\n # split the value up by commas
1325 value = ",".join(["'%s'"%x for x in value.split(",")])
1326 elif("string" in ty):\n #surround string with quotation marks
1327 value = "%s"%(value)\n # okay now done with everything
1328 call= self._func%(ty)\n if(name):
1329 return"%s=%s(%s)"%(name,call,value)\n return"%s(%s)"%(call,value)\n
1330 class ServerHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):\n
1331 def do_GET(self):\n if(self.path == "/index.html"):
1332 # find out what cfg html folders we have below
1333 # and add each main html page to the index\n li = os.listdir(".")
1335 dirs = [x for x in li if os.path.isdir(x) and x.endswith(dEnd)]
1337 names = [os.path.join(x,name) for x in dirs if name in os.listdir(x)]
1338 tmpte = '<li><a href ="%(n)s">%(s)s</a></li>'
1339 lis = [tmpte%{"n":x,"s":os.path.split(x)[0].replace(dEnd, "")}
1340 for x in names]\n with open("index.html", 'w') as f:
1341 f.write(\"""\n<!DOCTYPE html>\n<html>\n <head>
1342 <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
1343 <title>cfg-browser</title>\n </head>\n <body>
1344 <h4>Configuration files:</h4>\n <ul>\n %s\n </ul>\n </body>
1345 </html>\n \"""%("".join(lis)))\n
1346 return SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)\n
1348 ctype,pdict= cgi.parse_header(self.headers.getheader('content-type'))
1349 bdy = cgi.parse_multipart(self.rfile,pdict)
1350 ch= " ".join(bdy[bdy.keys()[0]])\n self.conversion(eval(ch))
1351 self.writeFile()\n print "finished writing"\n
1352 def conversion(self, json):\n # Need to convert my json into config
1353 result = CfgConvert(json)._doConversion()
1354 with open("changed_cfg.py", 'w')as f:\n f.write(result)\n
1355 def writeFile(self):\n with open("changed_cfg.py", 'rb') as f:
1356 self.send_response(200)
1357 self.send_header("Content-Type", 'text/html')
1358 self.send_header("Content-Disposition",
1359 'attachment; filename="changed_cfg.py"')
1360 fs = os.fstat(f.fileno())
1361 self.send_header("Content-Length", str(fs.st_size))
1362 self.end_headers()\n shutil.copyfileobj(f, self.wfile)\n
1363 def main(port=8000, reattempts=5):\n if(port <1024):
1364 print \"""This port number may be refused permission.
1365 It is better to use a port number > 1023.\"""\n try:
1366 Handler = ServerHandler
1367 httpd = SocketServer.TCPServer(("", port), Handler)
1368 print "using port", port
1369 print "Open http://localhost:%s/index.html in your browser."%(port)
1370 httpd.serve_forever()\n except socket.error as e:
1371 if(reattempts >0 and e[0] == errno.EACCES):
1372 print "Permission was denied."
1373 elif(reattempts >0 and e[0]== errno.EADDRINUSE):
1374 print "Address %s is in use."%(port)\n else:\n raise
1375 print "Trying again with a new port number."\n if(port < 1024):
1376 port = 1024\n else:\n port = port +1
1377 main(port, reattempts-1)\n\nif __name__ == "__main__":\n import sys
1378 if(len(sys.argv)>1):\n try:\n port = int(sys.argv[1])
1379 main(port)\n sys.exit() \n except ValueError:
1380 print "Integer not valid, using default port number."\n main()
1386 if(os.path.isdir(x)):
1388 allItems = os.listdir(x)
1389 py = [os.path.join(x,y)
for y
in allItems
if y.endswith(
".py")]
1395 for y
in os.listdir(x):
1396 path = os.path.join(x,y)
1397 if(os.path.isdir(path)):
1399 for z
in os.listdir(path)]))
1400 elif(x.endswith(
".py")):
1406 def main(args,helperDir,htmlFile,quiet, noServer):
1407 dirName =
"%s-cfghtml"
1415 tmpte =
'<li><a href ="%(n)s">%(s)s</a></li>'
1421 name = os.path.split(x)[1].
replace(
".py",
"")
1422 dirN = dirName%(name)
1430 if not os.path.exists(baseDir):
1431 os.makedirs(baseDir)
1434 lowerHTML = os.path.join(baseDir, htmlFile)
1435 helper = os.path.join(helperDir,
"")
1436 helperdir = os.path.join(baseDir, helper,
"")
1437 if not os.path.exists(helperdir):
1438 os.makedirs(helperdir)
1439 print "Calculating", x
1441 u =
unscheduled(x, lowerHTML, quiet, helper,helperdir)
1442 except Exception
as e:
1443 print "File %s is a config file but something went wrong"%(x)
1446 print "Finished with", x
1447 if(
not u._computed
and dirCreated):
1449 shutil.rmtree(baseDir)
1452 lis += tmpte%{
"n":os.path.join(dirN,htmlFile),
"s":name}
1453 with open(
"index.html",
'w')
as f:
1458 <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
1459 <title>cfg-browser</title>
1462 <h4>Configuration files:</h4>
1470 print "Sorry, no configuration files were found."
1472 print "Finished dealing with configuration files."
1476 print "Starting the python server.."
1481 if __name__ ==
"__main__":
1482 import sys, os, imp, shutil
1483 from optparse
import OptionParser
1484 parser = OptionParser(usage=
"%prog <cfg-file> ")
1485 parser.add_option(
"-q",
"--quiet",
1486 action=
"store_true", dest=
"_quiet", default=
False,
1487 help=
"Print minimal messages to stdout")
1490 parser.add_option(
"-s",
"--no_server",
1491 action=
"store_true", dest=
"_server", default=
False,
1492 help=
"Disable starting a python server to view "\
1493 "the html after finishing with config files.")
1494 parser.add_option(
"-r",
"--recurse", dest=
"_recurse",action=
"store_true",
1496 help=
"Search directories recursively for .py files.")
1499 helper_dir =
"cfgViewerJS"
1500 opts, args = parser.parse_args()
1503 distBaseDirectory=os.path.abspath(
1504 os.path.join(os.path.dirname(__file__),
".."))
1505 if (
not os.path.exists(distBaseDirectory)
or
1506 not "Vispa" in os.listdir(distBaseDirectory)):
1507 distBaseDirectory=os.path.abspath(
1508 os.path.join(os.path.dirname(__file__),
"../python"))
1509 if (
not os.path.exists(distBaseDirectory)
or
1510 not "Vispa" in os.listdir(distBaseDirectory)):
1511 distBaseDirectory=os.path.abspath(os.path.expandvars(
1512 "$CMSSW_BASE/python/FWCore/GuiBrowsers"))
1513 if (
not os.path.exists(distBaseDirectory)
or
1514 not "Vispa" in os.listdir(distBaseDirectory)):
1515 distBaseDirectory=os.path.abspath(os.path.expandvars(
1516 "$CMSSW_RELEASE_BASE/python/FWCore/GuiBrowsers"))
1518 distBaseDirectory=os.path.abspath(
1519 os.path.join(os.path.dirname(sys.argv[0]),
".."))
1520 sys.path.insert(0,distBaseDirectory)
1522 distBinaryBaseDirectory=os.path.join(baseDirectory,
"dist")
1523 sys.path.append(distBinaryBaseDirectory)
1524 from FWCore.GuiBrowsers.Vispa.Plugins.ConfigEditor
import ConfigDataAccessor
1526 recurse = opts._recurse
1527 doesNotExist = [x
for x
in args
if not os.path.exists(x)]
1528 if(len(doesNotExist)):
1530 for x
in doesNotExist:
1532 s +=
"%s does not exist.\n"%(x)
1535 if(len(args)==0
or len(doesNotExist)== len(args)):
1537 Either you provided no arguments, or the arguments provided do not exist.
1539 If you need help finding files, provide arguments "." -r and I will search
1540 recursively through the directories in the current directory.
1543 main(args,
"cfgViewerJS",
"main.html",opts._quiet, opts._server)
boost::dynamic_bitset append(const boost::dynamic_bitset<> &bs1, const boost::dynamic_bitset<> &bs2)
this method takes two bitsets bs1 and bs2 and returns result of bs2 appended to the end of bs1 ...
static std::string join(char **cmd)