def __getRvtNodes(self, manifest): rvtNodes = ArrayList() #print "manifest=%s" % manifest for key in manifest.keySet(): package = False node = manifest.get(key) try: # add the node rvtNode = HashMap() if node.get("hidden") != "True": relPath = node.get("id") # check if node is a package if relPath: package = (self.__getContentType(relPath) == "application/x-fascinator-package") else: relPath = key.replace("node", "blank") rvtNode.put("visible", True) rvtNode.put("title", node.get("title")) if package: subManifest = self.__readManifest(relPath) if subManifest: subManifest = subManifest.getJsonMap("manifest") rvtNode.put("children", self.__getRvtNodes(subManifest)) relPath = key.replace("node", "package") else: rvtNode.put("children", self.__getRvtNodes(node.getJsonMap("children"))) rvtNode.put("relPath", relPath) rvtNodes.add(rvtNode) except Exception, e: log.error("Failed to process node '%s': '%s'" % (node.toString(), str(e)))
def fuse_images(files,frames,model_dict): #first prepare the models and get the targettype models = ArrayList() images = ArrayList() is32bit = False; is16bit = False; is8bit = False; for file,frame in zip(files,frames): imp=IJ.openImage(file) if ( imp.getType() == ImagePlus.GRAY32 ): is32bit = True elif ( imp.getType() == ImagePlus.GRAY16 ): is16bit = True elif ( imp.getType() == ImagePlus.GRAY8 ): is8bit = True images.add( imp ) models.add(model_dict{frame}) if ( is32bit ): imp = Fusion.fuse( FloatType, images, models, 2, True, 0, None, False, False, False ) elif ( is16bit ): imp = Fusion.fuse( UnsignedShortType(), images, models, 2, True, 0, None, False, False, False) elif ( is8bit ): imp = Fusion.fuse( UnsignedByteType, images, models, 2, True, 0, None, False, False, False ) else: IJ.log( "Unknown image type for fusion." ) return imp
def getMethodArgNames(self, moduleName, className, methodName): from java.util import ArrayList args = self.getMethodArgs(moduleName, className, methodName) argList = ArrayList() for a in args: argList.add(a) return argList
class FacetList: def __init__(self, name, results): self.__facetMap = HashMap() self.__facetList = ArrayList() facets = results.getFacets() if facets is None: return facet = facets.get(name) if facet is None: return facetData = facet.values() for value in facetData.keySet(): count = facetData.get(value) facet = Facet(name, value, count) self.__facetMap.put(value, facet) slash = value.rfind("/") if slash == -1: self.__facetList.add(facet) else: parent = self.__getFacet(value[:slash]) if parent is not None: parent.addSubFacet(facet) def __getFacet(self, name): return self.__facetMap.get(name) def getJsonList(self): jsonList = ArrayList() for facets in self.__facetList: jsonList.add(facets.getJson()) return jsonList
def substituteRule(cls, rule, theta): """ generated source for method substituteRule """ head = cls.substitute(rule.getHead(), theta) body = ArrayList() for literal in rule.getBody(): body.add(cls.substituteLiteral(literal, theta)) return GdlPool.getRule(head, body)
def run(self, ctx): engctx = ctx.getEnginesContext() if not engctx: print('Back-end engines not initialized') return projects = engctx.getProjects() if not projects: print('There is no opened project') return # get the first unit available units = RuntimeProjectUtil.findUnitsByType(projects[0], None, False) if not units: print('No unit available') return unit = units[0] print('Unit: %s' % unit) # retrieve the formatter, which is a producer of unit representations formatter = unit.getFormatter() # create an extra document (text document), wrap it in a representtion lines = ArrayList() lines.add(Line('There are two hard problems in computer science: cache invalidation, naming things, and off-by-one errors.')) lines.add(Line(' - Phil Karlton (and others)')) extraDoc = StaticTextDocument(lines) extraPres = UnitRepresentationAdapter(100, 'Quotes', False, extraDoc) # add the newly created representation to our unit, and notify clients # the second argument indicates that the presentation should be persisted when saving the project formatter.addPresentation(extraPres, True) unit.notifyListeners(JebEvent(J.UnitChange));
class FacetList: def __init__(self, name, json): self.__facetMap = HashMap() self.__facetList = ArrayList() entries = json.getList("facet_counts/facet_fields/" + name) for i in range(0, len(entries), 2): value = entries[i] count = entries[i+1] if count > 0: facet = Facet(name, value, count) self.__facetMap.put(value, facet) slash = value.rfind("/") if slash == -1: self.__facetList.add(facet) else: parent = self.__getFacet(value[:slash]) if parent is not None: parent.addSubFacet(facet) def __getFacet(self, name): return self.__facetMap.get(name) def getJsonList(self): jsonList = ArrayList() for facets in self.__facetList: jsonList.add(facets.getJson()) return jsonList
def __getRvtNodes(self, manifest): rvtNodes = ArrayList() #print "manifest=%s" % manifest for node in manifest: package = False try: # add the node rvtNode = HashMap() if not node.getHidden(): oid = node.getId() # check if node is a package if oid != "blank": package = (self.__getContentType(oid) == "application/x-fascinator-package") else: oid = node.getKey().replace("node", "blank") rvtNode.put("visible", True) rvtNode.put("title", node.getTitle()) if package: subManifest = self.__readManifest(oid) if subManifest is not None: rvtNode.put("children", self.__getRvtNodes(subManifest.getTopNodes())) oid = node.getKey().replace("node", "package") else: rvtNode.put("children", self.__getRvtNodes(node.getChildren())) rvtNode.put("relPath", oid) rvtNodes.add(rvtNode) except Exception, e: self.log.error("Failed to process node '%s': '%s'" % (node.toString(), str(e)))
def getSourceConjuncts(self): """ generated source for method getSourceConjuncts """ # These are the selected source conjuncts, not just the candidates. sourceConjuncts = ArrayList(len(self.sourceConjunctIndices)) for index in sourceConjunctIndices: sourceConjuncts.add(self.sourceConjunctCandidates.get(index)) return sourceConjuncts
def makeNextAssignmentValid(self): """ generated source for method makeNextAssignmentValid """ if self.nextAssignment == None: return # Something new that can pop up with functional constants... i = 0 while i < len(self.nextAssignment): if self.nextAssignment.get(i) == None: # Some function doesn't agree with the answer here # So what do we increment? incrementIndex(self.plan.getIndicesToChangeWhenNull().get(i)) if self.nextAssignment == None: return i = -1 i += 1 # Find all the unsatisfied distincts # Find the pair with the earliest var. that needs to be changed varsToChange = ArrayList() d = 0 while d < self.plan.getDistincts().size(): # The assignments must use the assignments implied by nextAssignment if term1 == term2: # need to change one of these varsToChange.add(self.plan.getVarsToChangePerDistinct().get(d)) d += 1 if not varsToChange.isEmpty(): # We want just the one, as it is a full restriction on its # own behalf changeOneInNext(Collections.singleton(varToChange))
def createMenuItems(self, context_menu): self.context = context_menu menu_list = ArrayList() menu_list.add(JMenuItem("Get Emails",actionPerformed=self.email_menu)) menu_list.add(JMenuItem("Generate Usernames",actionPerformed=self.users_menu)) return menu_list
def __init__(self): self.speed = 5; self.speedZoom = .01; self.m_systemID = HashedString("RTSCameraSystem") #private final static List<HashedString> usedComponents; #private final static List<HashedString> optionalComponents; #private final static Set<HashedString> writeToComponents; #private final static Set<HashedString> otherComponents; #private final static Set<HashedString> usedInterfaces; #private final static Set<HashedString> writeToInterfaces; components = ArrayList() components.add(RTSCameraComponent.getComponentStaticType()) self.m_usedComponents = Collections.unmodifiableList(components) components = ArrayList() components.add(CameraComponent.getComponentStaticType()) self.m_optionalComponents = Collections.unmodifiableList(components) writes = HashSet() writes.add(RTSCameraComponent.getComponentStaticType()) writes.add(CameraComponent.getComponentStaticType()) self.m_writeToComponents = Collections.unmodifiableSet(writes) self.m_otherComponents = Collections.emptySet() interfaces = HashSet() interfaces.add(SystemManager.inputInteface) self.m_usedInterfaces = Collections.unmodifiableSet(interfaces) self.m_writeToInterfaces = Collections.unmodifiableSet(HashSet(self.m_usedInterfaces))
def core(imp): pntsA = parsePoints(imp) # Points must be passed to the Clusterer in Java List of Clusterable. pntsAL = ArrayList() for apnt in pntsA: pntsAL.add(PosWrap(apnt[0], apnt[1], apnt[2])) awrap = pntsAL.get(0) pp = awrap.getPoint() #print pp clusterer = KMeansPlusPlusClusterer(Number_of_Cluster, Iteration) res = clusterer.cluster(pntsAL) outimp = imp.duplicate() for i in range(res.size()): if Verbose: IJ.log('Cluster: ' + str(i)) for apnt in res.get(i).getPoints(): xpos = apnt.getPoint()[0] ypos = apnt.getPoint()[1] zpos = apnt.getPoint()[2] if Verbose: IJ.log('... ' + str(xpos) + ', ' + str(ypos) + ', ' + str(zpos)) outimp.getStack().getProcessor(int(zpos)+1).putPixel(int(xpos), int(ypos), i+1) return outimp
def removeAnonymousPropositions(cls, pn): """ generated source for method removeAnonymousPropositions """ toSplice = ArrayList() toReplaceWithFalse = ArrayList() for p in pn.getPropositions(): if p.getInputs().size() == 1 and isinstance(, (Transition, )): continue if isinstance(sentence, (GdlProposition, )): if sentence.__name__ == cls.TERMINAL or sentence.__name__ == cls.INIT_CAPS: continue else: if name == cls.LEGAL or name == cls.GOAL or name == cls.DOES or name == cls.INIT: continue if p.getInputs().size() < 1: toReplaceWithFalse.add(p) continue if p.getInputs().size() != 1: System.err.println("Might have falsely declared " + p.__name__ + " to be unimportant?") toSplice.add(p) for p in toSplice: pn.removeComponent(p) if len(inputs) > 1: System.err.println("Programmer made a bad assumption here... might lead to trouble?") for input in inputs: for output in outputs: input.addOutput(output) output.addInput(input) for p in toReplaceWithFalse: print "Should be replacing " + p + " with false, but should do that in the OPNF, really; better equipped to do that there"
class Facet: def __init__(self, key, value, count): self.__name = value[value.rfind("/") + 1:] fq = '%s:"%s"' % (key, value) self.__facetQuery = URLEncoder.encode(fq, "UTF-8") self.__id = md5.new(fq).hexdigest() self.__count = count self.__subFacets = ArrayList() def getId(self): return self.__id def getName(self): return self.__name def getCount(self): return self.__count def getFacetQuery(self): return self.__facetQuery def addSubFacet(self, facet): self.__subFacets.add(facet) def getSubFacets(self): return self.__subFacets
def _sbi_list_arraylist(list): """convert a python list to an arraylist. subroutine for _sub_build_intentions_icl""" al = ArrayList() for el in list: al.add(el) return al
def cleanParentheses(cls, rule): """ generated source for method cleanParentheses """ cleanedHead = cls.cleanParentheses(rule.getHead()) cleanedBody = ArrayList() for literal in rule.getBody(): cleanedBody.add(cls.cleanParentheses(literal)) return GdlPool.getRule(cleanedHead, cleanedBody)
def __checkResultsMatch(self, criteria_item, item): if criteria_item.getAllowNulls() == "field_include_null": #If the query criteria allows nulls and the field is null, true if item.get(criteria_item.getSolr_field()) is None: return True #Some fields are lists so just handle lists solrvallist = ArrayList() solrval = item.getString(None, criteria_item.getSolr_field()); if solrval is None: solrvallist = item.getList(criteria_item.getSolr_field()); else: solrvallist.add(solrval) #If the query's matching criteria uses 'equals', check that it's an exact match for solrval in solrvallist: if criteria_item.getMatchingOperator() == "field_match": if String(String(solrval).trim()).equalsIgnoreCase(String(criteria_item.getValue()).trim()): #self.log.debug("Matched at: field_match --> %s == %s" %(solrval, criteria_item.getValue())) #self.log.debug("criteria_item.getSolr_field() -> " + criteria_item.getSolr_field()) #self.log.debug("solrvallist:%s" % solrvallist ) return True else: #This is a contains search if solrval.lower().find(criteria_item.getValue().lower()) != -1: return True return False
def readCSV(filepath): reader = CSVReader(FileReader(filepath), ",") ls = reader.readAll() data = ArrayList() for item in ls: data.add(item) return data
def createMenuItems(self, context_menu): self.context = context_menu menu_list = ArrayList() menu_list.add(JMenuItem("Create Wordlist", actionPerformed=self.wordlist_menu)) return menu_list
class Facet: def __init__(self, key, value, count): self.__key = key self.__value = URLEncoder.encode(value, "UTF-8") self.__count = count self.__subFacets = ArrayList() def getName(self): name = URLDecoder.decode(self.__value, "UTF-8") slash = name.rfind("/") return name[slash+1:] def getKey(self): return self.__key def getValue(self): return self.__value def getCount(self): return self.__count def addSubFacet(self, facet): self.__subFacets.add(facet) def getSubFacets(self): return self.__subFacets def getFacetQuery(self): return '%s:"%s"' % (self.__key, self.__value) def getId(self): return md5.new(URLDecoder.decode(self.getFacetQuery(), "UTF-8")).hexdigest()
def _prepareKey(keysString): # e.g. keysString = "Test/HelloWorld/Java/-/message_text" # myKey contains either an error message or a Key. global myKey majorComponents = ArrayList() minorComponents = ArrayList() global errorMessage if not isinstance (keysString, str): errorMessage = "ERROR: Please enter a String as Key." return keysArray = keysString.split("/") isMajor = True for i in range (0, len(keysArray)): if (keysArray [i] == "-"): isMajor = False if (isMajor): majorComponents.add(keysArray [i]) else: if (keysArray [i] != "-"): minorComponents.add (keysArray [i]) if ((len (majorComponents) > 0) & (len (minorComponents) > 0)): myKey = Key.createKey(majorComponents, minorComponents) elif ((len (majorComponents) > 0) & (len (minorComponents) <= 0)): myKey = Key.createKey(majorComponents) else: errorMessage = "ERROR: The String could not be transformed to a Key." return return myKey
def createMenuItems(self, context_menu): self.context = context_menu menu_list = ArrayList() menu_list.add(JMenuItem("Wyslij do Bing", actionPerformed = self.bing_menu)) return manu_list
def createMenuItems(self, context_menu): self.context = context_menu menu_list = ArrayList() menu_list.add(JMenuItem("Utworz liste slow", actionpreformed = self.wordlist_menu)) return menu_list
def getVariableNames(cls, gdl): """ generated source for method getVariableNames """ variables = cls.getVariables(gdl) variableNames = ArrayList() for variable in variables: variableNames.add(variable.__name__) return variableNames
def illustrate(self, script_path, script_params, script_params_file): """ Runs an Illustrate on the script. Simulates GruntParser.processIllustrate Returns JSON Illustrate results as a string """ # Restore stdout sys.stdout = self.originalOut # Bust UDF Cache self.bust_udf_cache() os = ByteArrayOutputStream() ps = PrintStream(os) params = ArrayList() for param in script_params: params.add("%s=%s" % (param['name'],param['value'])) files = ArrayList() if script_params_file: files.add(script_params_file) try: self.grunt.parser.loadScript(script_path, params, files) self.pigServer.getExamples(None, True, ps, "json") except JavaException, e: print "java exception" print ExceptionUtils.getStackTrace(e) return HawkScriptError.getHawkScriptError(e).toJSON()
def getProps(self, ps, imageCache, f, nature, editor, offset): '''java: List<ICompletionProposal> getProps(PySelection ps, ImageCache imageCache, File f, IPythonNature nature, PyEdit edit, int offset) ''' IPyCompletionProposal = editor.getIPyCompletionProposalClass() #@UnresolvedImport PyCompletionProposal = editor.getPyCompletionProposalClass() #@UnresolvedImport UIConstants = editor.getUIConstantsClass() #@UnresolvedImport #======================================================================================================================= # Prop #======================================================================================================================= class Prop(PyCompletionProposal): '''This is the proposal that Ctrl+1 will require ''' def __init__(self, assignToAttribsOfSelf, *args): PyCompletionProposal.__init__(self, *args) self.assignToAttribsOfSelf = assignToAttribsOfSelf def apply(self, document): '''java: public void apply(IDocument document) ''' self.assignToAttribsOfSelf.run() def getSelection(self, document): return None from java.util import ArrayList l = ArrayList(); l.add(Prop(self.assignToAttribsOfSelf, '', 0, 0, 0, self.getImage(imageCache, UIConstants.ASSIST_DOCSTRING), "Assign parameters to attributes", None, None, IPyCompletionProposal.PRIORITY_DEFAULT)); return l
def createMenuItems(self, invocation): """ Creates a context menu for beautifying and unbeautifying the request in editable message windows. """ if invocation.getToolFlag() not in [ IBurpExtenderCallbacks.TOOL_REPEATER, IBurpExtenderCallbacks.TOOL_PROXY, IBurpExtenderCallbacks.TOOL_INTRUDER ]: return if invocation.getInvocationContext() != IContextMenuInvocation.CONTEXT_MESSAGE_EDITOR_REQUEST: return menuItemList = ArrayList() messageInfo = invocation.getSelectedMessages()[0] requestBytes = messageInfo.getRequest() requestInfo = self._helpers.analyzeRequest(requestBytes) messageReference = self._getMessageReferenceFromBeautifyHeader(requestInfo, requestBytes) if messageReference != -1: def _unbeautifyClick(event): self._restoreParameters(messageReference, messageInfo) menuItemList.add(JMenuItem('Unbeautify Request', actionPerformed=_unbeautifyClick)) else: self._messageReference += 1 def _beautifyClick(event): self._simplifyParameters(self._messageReference, messageInfo) menuItemList.add(JMenuItem('Beautify Request', actionPerformed=_beautifyClick)) return menuItemList
def pyValToJavaObj(val): retObj = val valtype = type(val) if valtype is int: retObj = Integer(val) elif valtype is float: retObj = Float(val) elif valtype is long: retObj = Long(val) elif valtype is bool: retObj = Boolean(val) elif valtype is list: retObj = ArrayList() for i in val: retObj.add(pyValToJavaObj(i)) elif valtype is tuple: tempList = ArrayList() for i in val: tempList.add(pyValToJavaObj(i)) retObj = Collections.unmodifiableList(tempList) elif issubclass(valtype, dict): retObj = pyDictToJavaMap(val) elif issubclass(valtype, JavaWrapperClass): retObj = val.toJavaObj() return retObj
def test_number_transform(self): a = AtomicInteger(0) b = AtomicInteger(1) c = AtomicInteger(2) x = ArrayList() x.add(a) x.add(b) x.add(c) self.assertEqual(x.get(0).get(), 0) self.assertEqual(x.get(1).get(), 1) self.assertEqual(x.get(2).get(), 2)
def getAgates(shellUtils, installpath, sapitsOSH, OSHVResult): mapInstanceNameToAgate = HashMap() filePath = installpath + '\\config\\ItsRegistryWGATE.xml' data = shellUtils.safecat(filePath) logger.debug('got ItsRegistryWGATE file') if data == None or error(data): logger.error('Got: [', data, '] when performing command [ safecat ', filePath, '] - terminating script') else: builder = SAXBuilder(0) doc = builder.build(StringReader(data)) root = doc.getRootElement() localWgates = getElementByAttrValue(root, 'key', 'name', 'LocalWgates') wgates = localWgates.getChildren() it = wgates.iterator() while it.hasNext(): wgate = it.next() value = wgate.getAttributeValue('name') if value.find('WGATE_') >= 0: instancesRoot = getElementByAttrValue(wgate, 'key', 'name', 'Instances') instances = instancesRoot.getChildren() itInstances = instances.iterator() while itInstances.hasNext(): instance = itInstances.next() instanceName = instance.getAttributeValue('name') logger.debug(instanceName) agatesRoot = getElementByAttrValue(instance, 'key', 'name', 'Agates') agates = agatesRoot.getChildren() itAgates = agates.iterator() while itAgates.hasNext(): agate = itAgates.next() agateHost = getElementByAttrValue( agate, 'value', 'name', 'Host') host = agateHost.getText() agates = mapInstanceNameToAgate.get(instanceName) if agates == None: agates = ArrayList() mapInstanceNameToAgate.put(instanceName, agates) try: ip = netutils.getHostAddress(host) hostOSH = modeling.createHostOSH(ip) OSHVResult.add(hostOSH) agateOSH = modeling.createApplicationOSH( 'sap_its_agate', 'ITS_AGATE_' + ip, hostOSH) OSHVResult.add(agateOSH) agates.add(agateOSH) except: logger.warn('Failed resolving IP for agate host ', host) return mapInstanceNameToAgate
def getProps(self, ps, imageCache, f, nature, editor, offset): '''java: List<ICompletionProposal> getProps(PySelection ps, ImageCache imageCache, File f, IPythonNature nature, PyEdit edit, int offset) ''' oProp = Prop(self.proposal, '', 0, 0, 0, self.getImage(imageCache, UIConstants.ASSIST_DOCSTRING), self.proposal.description, None, None, IPyCompletionProposal.PRIORITY_DEFAULT) l = ArrayList() l.add(oProp) return l
def createMenuItems(self, invocation): self.context = invocation menulist = ArrayList() # set a menu item with double click menulist.add( JMenuItem("Create a site map - OpenApi", actionPerformed=self.swaggermenu)) return menulist
def createMenuItems(self, invocation): """ Create a menu item on other tabs to allow them to send requests to Timing Attack """ self.context = invocation menuList = ArrayList() self.messageList = invocation.getSelectedMessages() menuItem = JMenuItem("Send to Timing Attack", actionPerformed=self.requestSent) menuList.add(menuItem) return menuList
def _get_args_as_java_array(*args): """ Convert the Python args list into a Java array of strings. :param args: the args list :return: the Java array of strings """ result = JArrayList() if args is not None and len(args) > 0: for arg in args: result.add(str(arg)) return result.toArray()
def setAccSeqNames(self,seq_names): accl = self.linac_wizard_document.getAccl() if(len(seq_names) == 0): accSeq = null self.linac_wizard_document.setAccSeq(accSeq) return lst = ArrayList() for seqName in seq_names: lst.add(accl.getSequence(seqName)) accSeq = AcceleratorSeqCombo("SEQUENCE", lst) self.linac_wizard_document.setAccSeq(accSeq)
def createMenuItems(self, invocation): self._context = invocation menuList = ArrayList() invocation_allowed = [ invocation.CONTEXT_MESSAGE_EDITOR_REQUEST, invocation.CONTEXT_PROXY_HISTORY, invocation.CONTEXT_TARGET_SITE_MAP_TABLE ] if self._context.getInvocationContext() in invocation_allowed and len( self._context.selectedMessages) == 1: parentMenu = JMenu('Exporter to') menuItemPythonRequest = JMenuItem( "Python Request", actionPerformed=self.asPythonRequest) menuItemCURL = JMenuItem("cURL", actionPerformed=self.asCURL) menuItemWget = JMenuItem("Wget", actionPerformed=self.asWget) menuItemPhpRequest = JMenuItem("PHP HTTP_Request2", actionPerformed=self.asPHPRequest) menuItemGo = JMenuItem("GO Native", actionPerformed=self.asGO) menuItemNodeRequest = JMenuItem( "NodeJS Request", actionPerformed=self.asNodeJSRequest) menuItemJQueryAjax = JMenuItem("jQuery AJAX", actionPerformed=self.asJQueryAjax) menuItemPowerShell = JMenuItem("PowerShell", actionPerformed=self.asPowerShell) menuItemPerl = JMenuItem("Perl LWP", actionPerformed=self.asPerl) parentMenu.add(menuItemCURL) parentMenu.add(menuItemWget) parentMenu.add(menuItemPythonRequest) parentMenu.add(menuItemPerl) parentMenu.add(menuItemPhpRequest) parentMenu.add(menuItemGo) parentMenu.add(menuItemNodeRequest) parentMenu.add(menuItemJQueryAjax) parentMenu.add(menuItemPowerShell) menuList.add(parentMenu) # Request info iRequestInfo = self._helpers.analyzeRequest( self._context.getSelectedMessages()[0]) self.headers = iRequestInfo.getHeaders() self.parameters = iRequestInfo.getParameters() self.method = iRequestInfo.getMethod() self.contentType = iRequestInfo.getContentType() self.url = iRequestInfo.getUrl().toString() self.payload = ''.join( map(chr, self._context.getSelectedMessages()[0].getRequest())).split( '\r\n\r\n')[1] return menuList
def createNdarrayFromBuffer(self, buffer): DirectNDArray = jep.findClass("jep.DirectNDArray") from java.util import ArrayList # Start off with a pyjobject which is a DirectNDArray dndarray = DirectNDArray(buffer) from java.util import ArrayList a = ArrayList() a.add(dndarray) # Getting the same object from a java method triggers the automatic # conversion to an ndarray. return a.get(0)
def createMenuItems(self, context_menu): """ JMenuItem本质上是一个继承自AbstractButton的按钮,不过它又不完全等同于按钮。 当鼠标经过某个菜单项时,Swing就认为该菜单项被选中,但并不会触发任何事件; 当用户在菜单项上释放鼠标,此时Swing也会认为该选项被选中,并触发事件完成相应的操作 """ self.context = context_menu menu_list = ArrayList() menu_list.add(JMenuItem("Send to Bing", actionPerformed=self.bing_menu)) return menu_list
def _createAggregateScoreCollector(self, query, keyName): scoreCollectors = ArrayList().of_( ScoreSuperCollector if self._multithreaded else ScoreCollector) for coreName in query.cores: rankQuery = query.rankQueryFor(coreName) if rankQuery: scoreCollector = self.call[coreName].scoreCollector( keyName=query.keyName(coreName), query=rankQuery) scoreCollectors.add(scoreCollector) constructor = AggregateScoreSuperCollector if self._multithreaded else AggregateScoreCollector return constructor( keyName, scoreCollectors) if scoreCollectors.size() > 0 else None
def loadBundle(bundleFile, setFilesDict=None, width=-1, height=-1, times="", clear=1): if (setFilesDict != None): setFiles = ArrayList() keys = setFilesDict.keys() for k in keys: setFiles.add(k) setFiles.add(setFilesDict.get(k)) else: setFiles = None islInterpreter.loadBundle(bundleFile,setFiles,width,height,times,clear);
def createMenuItems(self, invocation): self.context = invocation inv_context = invocation.getInvocationContext() if inv_context == 7: #not a valid menu return menuList = ArrayList() menuItem = JMenuItem("Get Depth Instance", actionPerformed=self.getDepthInstance) menuList.add(menuItem) return menuList
def createMenuItems(self, IContextMenuInvocation): self.selectedRequest = IContextMenuInvocation.getSelectedMessages() menuItemList = ArrayList() menuItemList.add( JMenuItem( "Refresh this site map entry with new request (no cookies)", actionPerformed=self.onClickNoCookies)) menuItemList.add( JMenuItem( "Refresh this site map entry with new request (add cookies from jar)", actionPerformed=self.onClickCookies)) return menuItemList
def createMenuItems(self, invocation): """Called when a context menu is invoked in Burp.""" from javax.swing import JMenuItem customMenuItem = JMenuItem("Create Custom Issue") contextMenuListener = ContextMenuListener(invocation) customMenuItem.addActionListener(contextMenuListener) from java.util import ArrayList menuArray = ArrayList() menuArray.add(customMenuItem) return menuArray
def executeQuery(self, luceneQuery, start=None, stop=None, sortKeys=None, facets=None, filterQueries=None, suggestionRequest=None, filter=None, dedupField=None, dedupSortField=None, scoreCollector=None, drilldownQueries=None, keyCollector=None, **kwargs): t0 = time() stop = 10 if stop is None else stop start = 0 if start is None else start collectors = [] resultsCollector = topCollector = self._topCollector(start=start, stop=stop, sortKeys=sortKeys) dedupCollector = None if dedupField: constructor = DeDupFilterSuperCollector if self._multithreaded else DeDupFilterCollector resultsCollector = dedupCollector = constructor(dedupField, dedupSortField, topCollector) collectors.append(resultsCollector) if facets: facetCollector = self._facetCollector() collectors.append(facetCollector) if keyCollector: collectors.append(keyCollector) if self._multithreaded: multiSubCollectors = ArrayList().of_(SuperCollector) for c in collectors: multiSubCollectors.add(c) collector = MultiSuperCollector(multiSubCollectors) if self._multithreaded else MultiCollector.wrap(collectors) if scoreCollector: scoreCollector.setDelegate(collector) collector = scoreCollector filter_ = self._filterFor(filterQueries, filter) if drilldownQueries: luceneQuery = self.createDrilldownQuery(luceneQuery, drilldownQueries) self._index.search(luceneQuery, filter_, collector) total, hits = self._topDocsResponse(topCollector, start=start, dedupCollector=dedupCollector if dedupField else None) response = LuceneResponse(total=total, hits=hits, drilldownData=[]) if dedupCollector: response.totalWithDuplicates = dedupCollector.totalHits if facets: response.drilldownData.extend(self._facetResult(facetCollector, facets)) if suggestionRequest: response.suggestions = self._index.suggest(**suggestionRequest) response.queryTime = millis(time() - t0) raise StopIteration(response) yield
def createMenuItems(self, invocation): self.context = invocation menuList = ArrayList() menuItem = JMenuItem( "Generate forced browsing wordlist from selected items", actionPerformed=self.createWordlistFromSelected) menuList.add(menuItem) menuItem = JMenuItem( "Generate forced browsing wordlist from all hosts in scope", actionPerformed=self.createWordlistFromScope) menuList.add(menuItem) return menuList
def run(self, ctx): engctx = ctx.getEnginesContext() if not engctx: print('Back-end engines not initialized') return projects = engctx.getProjects() if not projects: print('There is no opened project') return # get the first unit available units = RuntimeProjectUtil.findUnitsByType(projects[0], None, False) if not units: print('No unit available') return unit = units[0] print('Unit: %s' % unit) # retrieve the formatter, which is a producer of unit representations formatter = unit.getFormatter() # create a table document columnLabels = Arrays.asList('Key', 'Value', 'Comment') rows = ArrayList() rows.add( TableRow(Arrays.asList(Cell('foo'), Cell('bar'), Cell('none')))) rows.add( TableRow( Arrays.asList(Cell('type'), Cell('integer'), Cell('unset')))) extraDoc = StaticTableDocument(columnLabels, rows) extraPres0 = UnitRepresentationAdapter(101, 'Demo Table', False, extraDoc) # create a tree document columnLabels = Arrays.asList('Key', 'Value') root = KVNode('foo', 'bar') roots = Arrays.asList(root) root.addChild(KVNode('quantified', 'self')) root.addChild(KVNode('galaxy', 'milky way')) node = KVNode('black hole', '42') node.setClassId(ItemClassIdentifiers.INFO_DANGEROUS) root.addChild(node) extraDoc = StaticTreeDocument(roots, columnLabels, -1) extraPres1 = UnitRepresentationAdapter(102, 'Demo Tree', False, extraDoc) # add the newly created presentations to our unit, and notify clients # the second argument indicates that the presentation should be persisted when saving the project formatter.addPresentation(extraPres0, True) formatter.addPresentation(extraPres1, True) unit.notifyListeners(JebEvent(J.UnitChange))
def getMaps(): from java.util import ArrayList jmaps = ArrayList(len(maps)) for m in maps: j = m.toJavaObj() jmaps.add(j) for k, v in globals().iteritems(): if v is m: j.setInstanceName(k) break return jmaps
def exportAll(): try: ALSBConfigurationMBean = findService( "ALSBConfiguration", "com.bea.wli.sb.management.configuration.ALSBConfigurationMBean") print "ALSBConfiguration MBean found" print project if project == "None": ref = Ref.DOMAIN collection = Collections.singleton(ref) if passphrase == None: print "Export the config" theBytes = ALSBConfigurationMBean.export( collection, true, None) else: print "Export and encrypt the config" theBytes = ALSBConfigurationMBean.export( collection, true, passphrase) else: ref = Ref.makeProjectRef(project) print "Export the project", project collection = Collections.singleton(ref) theBytes = ALSBConfigurationMBean.exportProjects( collection, passphrase) aFile = File(exportJar) out = FileOutputStream(aFile) out.write(theBytes) out.close() print "ALSB Configuration file: " + exportJar + " has been exported" if customFile != "None": print collection query = EnvValueQuery( None, Collections.singleton(EnvValueTypes.WORK_MANAGER), collection, false, None, false) customEnv = FindAndReplaceCustomization( 'Set the right Work Manager', query, 'Production System Work Manager') print 'EnvValueCustomization created' customList = ArrayList() customList.add(customEnv) print customList aFile = File(customFile) out = FileOutputStream(aFile) Customization.toXML(customList, out) out.close() print "ALSB Dummy Customization file: " + customFile + " has been created" except: raise
def getProps(self, ps, imageCache, f, nature, editor, offset): '''java: List<ICompletionProposal> getProps(PySelection ps, ImageCache imageCache, File f, IPythonNature nature, PyEdit edit, int offset) ''' l = ArrayList() l.add( Prop(self.assignToAttribsOfSelf, '', 0, 0, 0, self.getImage(imageCache, UIConstants.ASSIST_DOCSTRING), "Assign parameters to attributes", None, None, IPyCompletionProposal.PRIORITY_DEFAULT)) return l
def executeQuery(self, query): r'@types: TableQueryRfc -> ?' from java.util import ArrayList inFieldValues = ArrayList() for value in query.inFieldValues: inFieldValues.add(value) whereClauses = query.whereClause and (query.whereClause, ) or None desiredFieldsRepr = ','.join(query.desiredFields) r = self.__sapUtils.executeQuery(query.tableName, whereClauses, desiredFieldsRepr, query.inField, inFieldValues) return query.parseResult(r)
def buildAndExecuteIhfsQuery(self, tableName, selectTableColumnList, queryPredicateTupleList, orderByList=None, groupByList=None): ihfsQueryHelper = IhfsQueryHelper.getInstance() tableName = tableName.upper() javaSelectColumnList = None if selectTableColumnList is not None: javaSelectColumnList = ArrayList() for selectTableColumn in selectTableColumnList: selectTableColumn = selectTableColumn.upper() if selectTableColumn.startswith(tableName): javaSelectColumnList.add(selectTableColumn) else: javaSelectColumnList.add(tableName + "." + selectTableColumn) queryHelperPredicateList = ArrayList() for conjunction, tableColumnName, operator, predicateValue in queryPredicateTupleList: if isinstance(predicateValue, list): javaQueryPredicate = ihfsQueryHelper.createQueryPredicateInHelper( conjunction, tableColumnName, operator, javaList) else: javaQueryPredicate = ihfsQueryHelper.createQueryPredicateHelper( conjunction, tableColumnName, operator, predicateValue) queryHelperPredicateList.add(javaQueryPredicate) javaOrderByList = None if orderByList is not None: javaOrderByList = ArrayList() for orderBy in orderByList: javaOrderByList.add(orderBy) javaGroupByList = None if groupByList is not None: javaGroupByList = ArrayList() for groupBy in groupByList: javaGroupByList.add(groupBy) javaReturnList = ihfsQueryHelper.buildAndExecuteSingleTableQuery( tableName, javaSelectColumnList, queryHelperPredicateList, javaOrderByList, groupByList) if javaReturnList is not None: pyReturnList = self.translateIhfsJavaToPy(javaReturnList) else: pyReturnList = [] return pyReturnList
def build_intention_icl(agent): """builds an IclList representation of the agent's current intention structure. this representation only includes task tframes and their associated goals/tasks""" intentions = ArrayList() intention_structure = agent._intention_structure for root in intention_structure.get_root_tframes(): tree = _sub_build_intention_icl(agent, root) for iclstruct in tree: if not (isinstance(iclstruct, IclStruct)): raise AssertionError intentions.add(iclstruct) return IclList(intentions)
def decode(moduleName, **kwargs): mod = sys.modules[moduleName] exec 'dec = mod.' + moduleName + '(**kwargs)' result = dec.decode() resultList = ArrayList() if result is not None: for resultDict in result: if type(resultDict) == dict: hashmap = JUtil.pyDictToJavaMap(resultDict) resultList.add(hashmap) else: resultList.add(resultDict) return resultList
def createMenuItems(self, invocation): self.context = invocation itemContext = invocation.getSelectedMessages() if itemContext > 0: menuList = ArrayList() menuItem = swing.JMenuItem("Scan with SQLTruncScanner", None, actionPerformed=self.start_scan) menuList.add(menuItem) return menuList return None
def getHttpMessages(self): # Let's highlight the specific string in the response that triggered the issue strRes = self.helpers.bytesToString(self.reqres.getResponse()) marks = [None, None] # XXX: shim for python objects marks[0] = strRes.index('1337') marks[1] = marks[0] + 4 marks = array(marks, 'i') marksList = ArrayList() marksList.add(marks) reqresMark = self.callbacks.applyMarkers(self.reqres, None, marksList) rra = [reqresMark] return rra
def getColumnsToGet(self): """ generated source for method getColumnsToGet """ if not self.meta.getStoreOptions().getStoreType() == StoreOptions.StoreType.SLICE: raise IllegalArgumentException("unsupported store type") plane = Plane(Range(self.meta.getxSize()), Range(self.meta.getySize())) subPlane = Plane(self.xRange, self.yRange) if plane == subPlane: return None columnsToGet = ArrayList() points = BlockUtil.calcBlockPointsCanCoverSubPlane(plane, subPlane, self.meta.getStoreOptions().getxSplitCount(), self.meta.getStoreOptions().getySplitCount()) for point in points: columnsToGet.add(String.format(DATA_BLOCK_COL_NAME_FORMAT, point.getX(), point.getY())) return columnsToGet
def load_profile(filename): fh = open(filename, 'r') lines = fh.readlines() profile_points = ArrayList() for line in lines[1:]: fields = line.split("\t") if len(fields) != 2: continue x, z = map(lambda x: x.replace(",", ""), fields) profile_points.add( jarray.array( [float(x) / 0.3048, float(z) / 0.3048], 'd')) fh.close() return profile_points
def createMenuItems(self, invocation): global invocations invocations = invocation menuItemList = ArrayList() #self._contextMenuData = contextMenuInvocation.getSelectedMessages() submenu = JMenu(self._actionName) for menuitem in sorted(self.menuitems): submenu.add(menuitem) menuItemList.add(submenu) return menuItemList
def convertStringArray(self, jsArray): result = ArrayList((Long),) try: for i in range(0,jsArray.__len__()): result.add(Long(jsArray.get(i))) except Exception,e: GWT.log(u"Failed to convert String array ", e)