Esempio n. 1
0
class ProverCache(object):
    """ generated source for class ProverCache """
    contents = Map()

    def __init__(self):
        """ generated source for method __init__ """
        self.contents = HashMap()

    # 
    # 	 * NOTE: The given sentence must have been renamed with a VariableRenamer.
    # 	 
    def contains(self, renamedSentence):
        """ generated source for method contains """
        return self.contents.containsKey(renamedSentence)

    def get(self, sentence, varRenamedSentence):
        """ generated source for method get """
        cacheContents = self.contents.get(varRenamedSentence)
        if cacheContents == None:
            return None
        results = HashSet()
        for answer in cacheContents:
            results.add(Unifier.unify(sentence, answer))
        return ArrayList(results)

    def put(self, sentence, renamedSentence, answers):
        """ generated source for method put """
        results = HashSet()
        for answer in answers:
            results.add(Substituter.substitute(sentence, answer))
        self.contents.put(renamedSentence, results)
Esempio n. 2
0
 def recordTemplates(self, description):
     """ generated source for method recordTemplates """
     templates = HashMap()
     for gdl in description:
         if not name.getValue() == "base":
             if not templates.containsKey(name):
                 templates.put(name, ArrayList())
             templates.get(name).add(rule)
     return templates
Esempio n. 3
0
 def getNextStates_0(self, state, role):
     """ generated source for method getNextStates_0 """
     nextStates = HashMap()
     roleIndices = getRoleIndices()
     for moves in getLegalJointMoves(state):
         if not nextStates.containsKey(move):
             nextStates.put(move, ArrayList())
         nextStates.get(move).add(self.getNextState(state, moves))
     return nextStates
Esempio n. 4
0
class Substitution(object):
    """ generated source for class Substitution """
    contents = Map()

    def __init__(self):
        """ generated source for method __init__ """
        self.contents = HashMap()

    def compose(self, thetaPrime):
        """ generated source for method compose """
        result = Substitution()
        result.contents.putAll(self.contents)
        result.contents.putAll(thetaPrime.contents)
        return result

    def contains(self, variable):
        """ generated source for method contains """
        return self.contents.containsKey(variable)

    def equals(self, o):
        """ generated source for method equals """
        if (o != None) and (isinstance(o, (Substitution, ))):
            return substitution.contents == self.contents
        return False

    def get(self, variable):
        """ generated source for method get """
        return self.contents.get(variable)

    def hashCode(self):
        """ generated source for method hashCode """
        return self.contents.hashCode()

    def put(self, variable, term):
        """ generated source for method put """
        self.contents.put(variable, term)

    # 
    # 	 * Creates an identical substitution.
    # 	 *
    # 	 * @return A new, identical substitution.
    # 	 
    def copy(self):
        """ generated source for method copy """
        copy = Substitution()
        copy.contents.putAll(self.contents)
        return copy

    def __str__(self):
        """ generated source for method toString """
        sb = StringBuilder()
        sb.append("{ ")
        for variable in contents.keySet():
            sb.append(variable + "/" + self.contents.get(variable) + " ")
        sb.append("}")
        return sb.__str__()
Esempio n. 5
0
 def recordLegalPropositions(self):
     """ generated source for method recordLegalPropositions """
     legalPropositions = HashMap()
     for proposition in propositions:
         if not (isinstance(, (GdlRelation, ))):
             continue 
         if relation.__name__.getValue() == "legal":
             if not legalPropositions.containsKey(r):
                 legalPropositions.put(r, HashSet())
             legalPropositions.get(r).add(proposition)
     return legalPropositions
Esempio n. 6
0
class KnowledgeBase(object):
    """ generated source for class KnowledgeBase """

    contents = Map()

    def __init__(self, description):
        """ generated source for method __init__ """
        self.contents = HashMap()
        for gdl in description:
            if not self.contents.containsKey(key):
                self.contents.put(key, ArrayList())
            self.contents.get(key).add(rule)

    @synchronized
    def fetch(self, sentence):
        """ generated source for method fetch """
        key = sentence.__name__
        if self.contents.containsKey(key):
            return self.contents.get(key)
        else:
            return ArrayList()
Esempio n. 7
0
def sort_deployeds():
    deployeds_per_key = HashMap()
    for _delta in deltas.deltas:
        deployed = _delta.deployedOrPrevious
        if deployed.type == "rh.TomcatWARModule":
            key = "%s___%s" % (deployed.appName, deployed.container.name)
            if deployeds_per_key.containsKey(key):
                deployeds_per_key.get(key).add(deployed)
            else:
                result = HashSet()
                result.add(deployed)
                deployeds_per_key.put(key, result)
    return deployeds_per_key
Esempio n. 8
0
def sort_deployeds():
    deployeds_per_key = HashMap()
    for _delta in deltas.deltas:
        deployed = _delta.deployedOrPrevious
        if deployed.type == "rh.TomcatWARModule":
            key = "%s___%s" % (deployed.appName, deployed.container.name)
            if deployeds_per_key.containsKey(key):
                deployeds_per_key.get(key).add(deployed)
            else:
                result = HashSet()
                result.add(deployed)
                deployeds_per_key.put(key, result)
    return deployeds_per_key
Esempio n. 9
0
 def recordGoalPropositions(self):
     """ generated source for method recordGoalPropositions """
     goalPropositions = HashMap()
     for proposition in propositions:
         #  Skip all propositions that aren't GdlRelations.
         if not (isinstance(, (GdlRelation, ))):
             continue 
         if not relation.__name__.getValue() == "goal":
             continue 
         if not goalPropositions.containsKey(theRole):
             goalPropositions.put(theRole, HashSet())
         goalPropositions.get(theRole).add(proposition)
     return goalPropositions
Esempio n. 10
0
 def makeLegalInputMap(self):
     """ generated source for method makeLegalInputMap """
     legalInputMap = HashMap()
     #  Create a mapping from Body->Input.
     inputPropsByBody = HashMap()
     for inputProp in inputPropositions.values():
         inputPropsByBody.put(inputPropBody, inputProp)
     #  Use that mapping to map Input->Legal and Legal->Input
     #  based on having the same Body proposition.
     for legalProps in legalPropositions.values():
         for legalProp in legalProps:
             if inputPropsByBody.containsKey(legalPropBody):
                 legalInputMap.put(inputProp, legalProp)
                 legalInputMap.put(legalProp, inputProp)
     return legalInputMap
Esempio n. 11
0
 def mergeBaseRelations(self, rels):
     """ generated source for method mergeBaseRelations """
     merges = HashMap()
     for rel in rels:
         if not merges.containsKey(name):
             merges.put(name, ArrayList())
         addRelToMerge(rel, merge)
     rval = HashSet()
     valConst = GdlPool.getConstant("val")
     for c in merges.keySet():
         body.add(c)
         for mergeSet in merge:
             Collections.sort(ms2, SortTerms())
             body.add(GdlPool.getFunction(valConst, ms2))
         rval.add(toAdd)
     return rval
Esempio n. 12
0
def readDataCSV(fp):
    reader = CSVReader(FileReader(fp), ",")
    ls = reader.readAll()
    tracks = HashMap()
    for idx, item in enumerate(ls):
        if idx > 0:
            if tracks.containsKey(int(item[0])):
                pass
            else:
                track = [[], [], [], []]
                tracks.put(int(item[0]), track)  # trackID in str.
            track = tracks.get(int(item[0]))
            track[0].append(int(item[1]))  # frame 0
            track[1].append(item[3])  # x 1
            track[2].append(item[4])  # y 2
            roi = Roi(int(item[5]), int(item[6]), int(item[7]), int(item[8]))
            track[3].append(roi)  # a roi 3
    return tracks
Esempio n. 13
0
    def updateAttributes(self, context, configurationAttributes):
        print "Idp extension. Method: updateAttributes"
        attributeContext = context.getAttributeContext()

        customAttributes = HashMap()
        customAttributes.putAll(attributeContext.getIdPAttributes())

        # Remove givenName attribute
        customAttributes.remove("givenName")

        # Update surname attribute
        if customAttributes.containsKey("sn"):
            customAttributes.get("sn").setValues(
                ArrayList(Arrays.asList(StringAttributeValue("Dummy"))))

        # Set updated attributes
        attributeContext.setIdPAttributes(customAttributes.values())

        return True
Esempio n. 14
0
class PagingWindow(UserList):
    def __init__(self, **kwargs):
        # The list is contained w/in self.data
        UserList.__init__(self)
        
        self.limitSize = 0      # Unbounded
        self.limitMin = False   # unbounded
        self.limitMax = False   # unbounded
        
        self.minElmIndx = -1
        self.minElmVal  = None
        self.maxElmIndx = -1
        self.maxElmVal  = None

        # Create a hash map for storing an object as well.
        self.hash = HashMap()

        opts = { 'limitSize' : self.optLimitSize,
                 'limitMin'  : self.optLimitMin,
                 'limitMax'  : self.optLimitMax,
                 
                 'preserveSmallest'  : self.optPreserveSmallest,
                 'preserveLargest'   : self.optPreserveLargest,
        }

        # Process each optional argumen.
        for k in kwargs.keys():
            optFunc = opts[k]
            if optFunc is None:
                raise LookupError("Option [k] is not supported by the PagingWindow class.")
            else:
                optFunc(kwargs[k])
        
        random.seed(time.time())
        
    def optLimitSize(self, _size):
        if type(_size).__name__ != "int":
            raise ValueError("limitSize parameter must be type int. Got type [{}].".format(type(_size).__name__))
        self.limitSize = _size
        
    def optLimitMin(self, _min):
        if type(_min).__name__ != "bool":
            raise ValueError("limitMin parameter must be type bool.")
        self.limitMin = _min

    def optLimitMax(self, _max):
        if type(_max).__name__ != "bool":
            raise ValueError("limitMax parameter must be type bool.")
        self.limitMax = _max
        
    def optPreserveSmallest(self, _small):
        if type(_small).__name__ != "bool":
            raise ValueError("preserveSmallest parameter must be type bool.")
        if _small:
            self.limitMin = False
            self.limitMax = True

    def optPreserveLargest(self, _large):
        if type(_large).__name__ != "bool":
            raise ValueError("preserveLargest parameter must be type bool.")
        if _large:
            self.limitMin = True
            self.limitMax = False


    def add(self, _key, _value = None):

        # print "==> value[{}] limitSize[{}]".format(_key, self.limitSize)
        # print "==> data.__len__[%d]" % self.data.__len__()

        dataLen = self.data.__len__()

        if dataLen < self.limitSize:
            ''' Here we add to the list when the list had not reached its
                max size.
            '''
            # print "..> appeding to data: [%s]" % _key
            self.data.append(_key)

            if _value is not None:
                # print " ++> added _value[{}]".format(_value)
                self.hash.put(_key, _value)

            # We should remove the sort on every insert.
            # Use sortedcontainers instead.
            self.data.sort()
        else:
            # print "..> not appending to data: [%s]" % _key

            insertMinOk = True
            insertMaxOk = True

            if self.limitMin:
                ''' If the new value is greater than the current minElement,
                    we may need to remove the current minElement to make room
                    for the new value.
                '''
                if self.data.__len__ > 0:
                    # The minElmIndx is always 0,
                    # unless the array has no data.
                    self.minElmIndx = 0
                else:
                    self.minElmIndx = -1
                if self.minElmIndx >= 0:
                    self.minElmVal = self.data[self.minElmIndx]
                    if _key < self.minElmVal:
                        insertMinOk = False
                        
            if self.limitMax:
                ''' If the new value is smaller than the current maxElement,
                    we may need to remove the current maxElement to make room
                    for the new value.
                '''
                self.maxElmIndx = self.data.__len__() - 1
                if self.maxElmIndx > 0:
                    self.maxElmVal = self.data[self.maxElmIndx]
                    if _key > self.maxElmVal:
                        insertMaxOk = False

            if self.limitMin and self.limitMax:
                     ''' Handle the case where it is ok to insert for either
                         case of limitMin and limitMax
                     '''
                     if insertMinOk and insertMaxOk:
                         # choseSize() may be a custom function that gets passed in.
                         side = self.choseSide(_key)
                         if side == 0:
                             raise AssertionError("chooseSide() should not return 0 as a result")
                         if side < 0:
                             if self.minElmVal is not None:
                                 self.data.remove(self.minElmVal)
                                 if self.hash.containsKey(self.minElmVal):
                                     self.hash.remove(self.minElmVal)
                         if side > 0:
                             if self.maxElmVal is not None:
                                 self.data.remove(self.maxElmVal)
                                 if self.hash.containsKey(self.maxElmVal):
                                     self.hash.remove(self.maxElmVal)
            else:
                if self.limitMin:
                    if insertMinOk:
                        if self.minElmVal is not None:
                            self.data.remove(self.minElmVal)
                            if self.hash.containsKey(self.maxElmVal):
                                self.hash.remove(self.maxElmVal)
                    else:
                        if self.data.__len__() + 1 > self.limitSize:
                            return False

                if self.limitMax:
                    if insertMaxOk:
                        if self.maxElmVal is not None:
                            self.data.remove(self.maxElmVal)
                            if self.hash.containsKey(self.maxElmVal):
                                self.hash.remove(self.maxElmVal)
                    else:
                        if self.data.__len__() + 1 > self.limitSize:
                            return False

            self.data.append(_key)
            if _value is not None:
                # print " ++> added _value[{}]".format(_value)
                self.hash.put(_key, _value)

            # We should remove the sort on every insert.
            # Possibly use sortedcontainers instead.
            self.data.sort()
            # Return True when a value is added
            return True

    def pop(self, indx):
        # Pop the 0 item from the list
        _key = super(UserList, self).pop(indx)

        # By default, return the key.
        retVal = _key

        # But, if the key has a corresponding value in the hash...
        if self.hash.containsKey(_key):
            # return the hash...
            retVal = [ _key, self.hash.get(_key) ]
            # and removed the object from the hash
            self.hash.remove(_key)

        return retVal

    def chooseSide(_key):
        r = random.getrandbits(1)

        if (r == 0):
            return -1
            
        if (r == 1):
            return 1

    def size(self):
        return self.data.__len__()
Esempio n. 15
0
class MappingGdlScrambler(GdlScrambler):
    """ generated source for class MappingGdlScrambler """
    scrambleMapping = Map()
    unscrambleMapping = Map()
    random = Random()
    scrambledPrefix = int()
    scrambledTokens = Stack()

    def __init__(self, theRandom):
        """ generated source for method __init__ """
        super(MappingGdlScrambler, self).__init__()
        self.random = theRandom
        self.scrambleMapping = HashMap()
        self.unscrambleMapping = HashMap()
        self.scrambledPrefix = 0
        self.scrambledTokens = Stack()
        for word in WordList.words:
            self.scrambledTokens.add(word)
        Collections.shuffle(self.scrambledTokens, self.random)

    class ScramblingRenderer(GdlRenderer):
        """ generated source for class ScramblingRenderer """
        def renderConstant(self, constant):
            """ generated source for method renderConstant """
            return scrambleWord(constant.getValue())

        def renderVariable(self, variable):
            """ generated source for method renderVariable """
            return scrambleWord(variable.__str__())

    class UnscramblingRenderer(GdlRenderer):
        """ generated source for class UnscramblingRenderer """
        def renderConstant(self, constant):
            """ generated source for method renderConstant """
            return unscrambleWord(constant.getValue())

        def renderVariable(self, variable):
            """ generated source for method renderVariable """
            return unscrambleWord(variable.__str__())

    def scramble(self, x):
        """ generated source for method scramble """
        return self.ScramblingRenderer().renderGdl(x)

    def unscramble(self, x):
        """ generated source for method unscramble """
        return GdlFactory.create(self.UnscramblingRenderer().renderGdl(GdlFactory.create(x)))

    def scrambles(self):
        """ generated source for method scrambles """
        return True

    def scrambleWord(self, realWord):
        """ generated source for method scrambleWord """
        if not shouldMap(realWord):
            return realWord
        if not self.scrambleMapping.containsKey(realWord):
            if realWord.startsWith("?"):
                fakeWord = "?" + fakeWord
            self.scrambleMapping.put(realWord, fakeWord)
            self.unscrambleMapping.put(fakeWord, realWord)
        return self.scrambleMapping.get(realWord)

    def unscrambleWord(self, fakeWord):
        """ generated source for method unscrambleWord """
        if not shouldMap(fakeWord):
            return fakeWord
        fakeWord = fakeWord.lower()
        if not self.unscrambleMapping.containsKey(fakeWord):
            return fakeWord
        return self.unscrambleMapping.get(fakeWord)

    def getRandomWord(self):
        """ generated source for method getRandomWord """
        if self.scrambledTokens.isEmpty():
            for word in WordList.words:
                self.scrambledTokens.add(word + self.scrambledPrefix)
            Collections.shuffle(self.scrambledTokens, self.random)
            self.scrambledPrefix += 1
        return self.scrambledTokens.pop()

    @classmethod
    def shouldMap(cls, token):
        """ generated source for method shouldMap """
        if GdlPool.KEYWORDS.contains(token.lower()):
            return False
        try:
            Integer.parseInt(token)
            return False
        except NumberFormatException as e:
        return True
Esempio n. 16
0
    def addSentenceForm(cls, form, model, components, negations, trueComponent, falseComponent, usingBase, usingInput, recursionForms, temporaryComponents, temporaryNegations, functionInfoMap, constantChecker, completedSentenceFormValues):
        """ generated source for method addSentenceForm """
        alwaysTrueSentences = model.getSentencesListedAsTrue(form)
        rules = model.getRules(form)
        for alwaysTrueSentence in alwaysTrueSentences:
            if alwaysTrueSentence.__name__ == cls.LEGAL or alwaysTrueSentence.__name__ == cls.NEXT or alwaysTrueSentence.__name__ == cls.GOAL:
                trueComponent.addOutput(prop)
                prop.addInput(trueComponent)
            components.put(alwaysTrueSentence, trueComponent)
            negations.put(alwaysTrueSentence, falseComponent)
            continue 
        if usingInput and form.__name__ == cls.DOES:
            for inputSentence in constantChecker.getTrueSentences(inputForm):
                components.put(doesSentence, prop)
            return
        if usingBase and form.__name__ == cls.TRUE:
            for baseSentence in constantChecker.getTrueSentences(baseForm):
                components.put(trueSentence, prop)
            return
        inputsToOr = HashMap()
        for rule in rules:
            varsInLiveConjuncts.addAll(GdlUtils.getVariables(rule.getHead()))
            while asnItr.hasNext():
                if assignment == None:
                    continue 
                ConcurrencyUtils.checkForInterruption()
                for literal in rule.getBody():
                    if isinstance(literal, (GdlSentence, )):
                        if constantChecker.isConstantForm(conjunctForm):
                            if not constantChecker.isTrueConstant(transformed):
                                asnItr.changeOneInNext(varsToChange, assignment)
                                componentsToConnect.add(None)
                            continue 
                        if conj == None:
                            conj = temporaryComponents.get(transformed)
                        if conj == None and SentenceModelUtils.inSentenceFormGroup(transformed, recursionForms):
                            temporaryComponents.put(transformed, tempProp)
                            conj = tempProp
                        if conj == None or isThisConstant(conj, falseComponent):
                            asnItr.changeOneInNext(varsInConjunct, assignment)
                            componentsToConnect.add(None)
                            continue 
                        componentsToConnect.add(conj)
                    elif isinstance(literal, (GdlNot, )):
                        if constantChecker.isConstantForm(conjunctForm):
                            if constantChecker.isTrueConstant(transformed):
                                asnItr.changeOneInNext(varsToChange, assignment)
                                componentsToConnect.add(None)
                            continue 
                        if isThisConstant(conj, falseComponent):
                            asnItr.changeOneInNext(varsInConjunct, assignment)
                            componentsToConnect.add(None)
                            continue 
                        if conj == None:
                            conj = temporaryNegations.get(transformed)
                        if conj == None and SentenceModelUtils.inSentenceFormGroup(transformed, recursionForms):
                            if positive == None:
                                positive = temporaryComponents.get(transformed)
                            if positive == None:
                                temporaryComponents.put(transformed, tempProp)
                                positive = tempProp
                            not_.addInput(positive)
                            positive.addOutput(not_)
                            temporaryNegations.put(transformed, not_)
                            conj = not_
                        if conj == None:
                            if positive == None:
                                continue 
                            if existingNotOutput != None:
                                componentsToConnect.add(existingNotOutput)
                                negations.put(transformed, existingNotOutput)
                                continue 
                            not_.addInput(positive)
                            positive.addOutput(not_)
                            negations.put(transformed, not_)
                            conj = not_
                        componentsToConnect.add(conj)
                    elif isinstance(literal, (GdlDistinct, )):
                    else:
                        raise RuntimeException("Unwanted GdlLiteral type")
                if not componentsToConnect.contains(None):
                    andify(componentsToConnect, andComponent, trueComponent)
                    if not isThisConstant(andComponent, falseComponent):
                        if not inputsToOr.containsKey(sentence):
                            inputsToOr.put(sentence, HashSet())
                        inputsToOr.get(sentence).add(andComponent)
                        if preventDuplicatesFromConstants:
                            asnItr.changeOneInNext(varsInLiveConjuncts, assignment)

        for entry in inputsToOr.entrySet():
            ConcurrencyUtils.checkForInterruption()
            for input in inputs:
                if isinstance(input, (Constant, )) or input.getInputs().size() == 0:
                    realInputs.add(input)
                else:
                    realInputs.add(input.getSingleInput())
                    input.getSingleInput().removeOutput(input)
                    input.removeAllInputs()
            cls.orify(realInputs, prop, falseComponent)
            components.put(sentence, prop)
        if form.__name__ == cls.TRUE or form.__name__ == cls.DOES:
            for sentence in model.getDomain(form):
                ConcurrencyUtils.checkForInterruption()
                components.put(sentence, prop)
	display_order.append(original_layer.relativeIndexOf(patch))

# Sort original indexed to put it in display order
original_indexed = zip(display_order, original_patches)
original_indexed = sorted(original_indexed, key=lambda x: x[0])

for i, patch in enumerate(target_patches):
	print patch.getTitle()
	cp.put(patch.getTitle(), patch)
	IJ.showProgress(i, target_patches.size())

IJ.log( "Assigning transformations..." );

for i, patch in original_indexed:
	print patch.getTitle()
	if cp.containsKey(patch.getTitle()):
		patch_title = patch.getTitle()[:-4]
		print patch.getId(), patch_title
		print patch.hasCoordinateTransform()

		target_patch = cp.get(patch.getTitle())
		target_patch.setCoordinateTransform(patch.getCoordinateTransform())
		target_patch.getAffineTransform().setTransform(patch.getAffineTransform())
		target_patch.updateInDatabase("transform")
		target_patch.updateBucket()

		# tform_file = folder + patch_title + '_original.xml'
		# tform_xml = open(tform_file, 'w')
		# tform_xml.write(patch.getCoordinateTransform().toXML('\t'))
	 	# tform_xml.close()
Esempio n. 18
0
class PropNetConverter(object):
    """ generated source for class PropNetConverter """
    #  An archive of Propositions, indexed by name. 
    propositions = Map()

    #  An archive of Components. 
    components = Set()

    # 
    # 	 * Converts a game description to a PropNet using the following process
    # 	 * (note that this method and all of the methods that it invokes assume that
    # 	 * <tt>description</tt> has already been flattened by a PropNetFlattener):
    # 	 * <ol>
    # 	 * <li>Transforms each of the rules in <tt>description</tt> into
    # 	 * equivalent PropNet Components.</li>
    # 	 * <li>Adds or gates to Propositions with more than one input.</li>
    # 	 * <li>Adds inputs that are implicitly specified by <tt>description</tt>.</li>
    # 	 * </ol>
    # 	 *
    # 	 * @param description
    # 	 *            A game description.
    # 	 * @return An equivalent PropNet.
    # 	 
    def convert(self, roles, description):
        """ generated source for method convert """
        self.propositions = HashMap()
        self.components = HashSet()
        for rule in description:
            if rule.arity() > 0:
                convertRule(rule)
            else:
                convertStatic(rule.getHead())
        fixDisjunctions()
        addMissingInputs()
        return PropNet(roles, self.components)

    # 
    # 	 * Creates an equivalent InputProposition for every LegalProposition where
    # 	 * none already exists.
    # 	 
    def addMissingInputs(self):
        """ generated source for method addMissingInputs """
        addList = ArrayList()
        for proposition in propositions.values():
            if isinstance(, (GdlRelation, )):
                if relation.__name__.getValue() == "legal":
                    addList.add(proposition)
        for addItem in addList:
            self.components.add(getProposition(GdlPool.getRelation(GdlPool.getConstant("does"), relation.getBody())))

    def convertConjunct(self, literal):
        """ generated source for method convertConjunct """
        if isinstance(literal, (GdlDistinct, )):
            link(constant, proposition)
            self.components.add(proposition)
            self.components.add(constant)
            return proposition
        elif isinstance(literal, (GdlNot, )):
            link(input, no)
            link(no, output)
            self.components.add(input)
            self.components.add(no)
            self.components.add(output)
            return output
        else:
            self.components.add(proposition)
            return proposition

    def convertHead(self, sentence):
        """ generated source for method convertHead """
        if sentence.__name__.getValue() == "next":
            link(preTransition, transition)
            link(transition, head)
            self.components.add(head)
            self.components.add(transition)
            self.components.add(preTransition)
            return preTransition
        else:
            self.components.add(proposition)
            return proposition

    def convertRule(self, rule):
        """ generated source for method convertRule """
        head = self.convertHead(rule.getHead())
        and_ = And()
        link(and_, head)
        self.components.add(head)
        self.components.add(and_)
        for literal in rule.getBody():
            link(conjunct, and_)

    def convertStatic(self, sentence):
        """ generated source for method convertStatic """
        if sentence.__name__.getValue() == "init":
            link(init, transition)
            link(transition, proposition)
            self.components.add(init)
            self.components.add(transition)
            self.components.add(proposition)
        constant = Constant(True)
        proposition = getProposition(sentence)
        link(constant, proposition)
        self.components.add(constant)
        self.components.add(proposition)

    def fixDisjunctions(self):
        """ generated source for method fixDisjunctions """
        fixList = ArrayList()
        for proposition in propositions.values():
            if proposition.getInputs().size() > 1:
                fixList.add(proposition)
        for fixItem in fixList:
            for input in fixItem.getInputs():
                i += 1
                if isinstance(, (GdlProposition, )):
                    disjunct = Proposition(GdlPool.getProposition(GdlPool.getConstant(proposition.__name__.getValue() + "-" + i)))
                else:
                    disjunct = Proposition(GdlPool.getRelation(GdlPool.getConstant(relation.__name__.getValue() + "-" + i), relation.getBody()))
                input.getOutputs().clear()
                link(input, disjunct)
                link(disjunct, or_)
                self.components.add(disjunct)
            fixItem.getInputs().clear()
            link(or_, fixItem)
            self.components.add(or_)

    def getProposition(self, sentence):
        """ generated source for method getProposition """
        if not self.propositions.containsKey(sentence):
            self.propositions.put(sentence, Proposition(sentence))
        return self.propositions.get(sentence)

    def link(self, source, target):
        """ generated source for method link """
        source.addOutput(target)
        target.addInput(source)
Esempio n. 19
0
class GameSelector(ActionListener):
    """ generated source for class GameSelector """

    theGameList = JComboBox()
    theRepositoryList = JComboBox()
    theSelectedRepository = GameRepository()
    theCachedRepositories = Map()

    class NamedItem(object):
        """ generated source for class NamedItem """

        theKey = str()
        theName = str()

        def __init__(self, theKey, theName):
            """ generated source for method __init__ """
            self.theKey = theKey
            self.theName = theName

        def __str__(self):
            """ generated source for method toString """
            return self.theName

    def __init__(self):
        """ generated source for method __init__ """
        super(GameSelector, self).__init__()
        self.theGameList = JComboBox()
        self.theGameList.addActionListener(self)
        self.theRepositoryList = JComboBox()
        self.theRepositoryList.addActionListener(self)
        self.theCachedRepositories = HashMap()
        self.theRepositoryList.addItem("games.ggp.org/base")
        self.theRepositoryList.addItem("games.ggp.org/dresden")
        self.theRepositoryList.addItem("games.ggp.org/stanford")
        self.theRepositoryList.addItem("Local Game Repository")

    def actionPerformed(self, e):
        """ generated source for method actionPerformed """
        if e.getSource() == self.theRepositoryList:
            if self.theCachedRepositories.containsKey(theRepositoryName):
                self.theSelectedRepository = self.theCachedRepositories.get(theRepositoryName)
            else:
                if theRepositoryName == "Local Game Repository":
                    self.theSelectedRepository = LocalGameRepository()
                else:
                    self.theSelectedRepository = CloudGameRepository(theRepositoryName)
                self.theCachedRepositories.put(theRepositoryName, self.theSelectedRepository)
            repopulateGameList()

    def getSelectedGameRepository(self):
        """ generated source for method getSelectedGameRepository """
        return self.theSelectedRepository

    def repopulateGameList(self):
        """ generated source for method repopulateGameList """
        theRepository = self.getSelectedGameRepository()
        theKeyList = ArrayList(theRepository.getGameKeys())
        Collections.sort(theKeyList)
        self.theGameList.removeAllItems()
        for theKey in theKeyList:
            if theGame == None:
                continue
            if theName == None:
                theName = theKey
            if 24 > len(theName):
                theName = theName.substring(0, 24) + "..."
            self.theGameList.addItem(self.NamedItem(theKey, theName))

    def getRepositoryList(self):
        """ generated source for method getRepositoryList """
        return self.theRepositoryList

    def getGameList(self):
        """ generated source for method getGameList """
        return self.theGameList

    def getSelectedGame(self):
        """ generated source for method getSelectedGame """
        try:
            return self.getSelectedGameRepository().getGame((self.theGameList.getSelectedItem()).theKey)
        except Exception as e:
            return None
Esempio n. 20
0
class PlayerPresenceManager(Subject):
    """ generated source for class PlayerPresenceManager """
    monitoredPlayers = Map()

    class PlayerPresenceChanged(Event):
        """ generated source for class PlayerPresenceChanged """

    class PlayerPresenceAdded(Event):
        """ generated source for class PlayerPresenceAdded """

    class PlayerPresenceRemoved(Event):
        """ generated source for class PlayerPresenceRemoved """

    @classmethod
    def isDifferent(cls, a, b):
        """ generated source for method isDifferent """
        return not Objects == a, b

    INFO_PING_PERIOD_IN_SECONDS = 1

    class PresenceMonitor(Thread):
        """ generated source for class PresenceMonitor """
        def run(self):
            """ generated source for method run """
            while True:
                try:
                    Thread.sleep(self.INFO_PING_PERIOD_IN_SECONDS)
                except InterruptedException as e:
                    e.printStackTrace()
                for key in keys:
                    if presence == None:
                        continue 
                    if presence.getStatusAge() > self.INFO_PING_PERIOD_IN_SECONDS * 1000:
                        presence.updateInfo()
                        if self.isDifferent(old_status, new_status):
                            notifyObservers(self.PlayerPresenceChanged())
                        elif self.isDifferent(old_name, new_name):
                            notifyObservers(self.PlayerPresenceChanged())

    def __init__(self):
        """ generated source for method __init__ """
        super(PlayerPresenceManager, self).__init__()
        self.monitoredPlayers = HashMap()
        loadPlayersJSON()
        if len(self.monitoredPlayers) == 0:
            try:
                #  When starting from a blank slate, add some initial players to the
                #  monitoring list just so that it's clear how it works.
                addPlayer("127.0.0.1:9147")
                addPlayer("127.0.0.1:9148")
            except InvalidHostportException as e:
        self.PresenceMonitor().start()

    @SuppressWarnings("serial")
    class InvalidHostportException(Exception):
        """ generated source for class InvalidHostportException """

    def addPlayerSilently(self, hostport):
        """ generated source for method addPlayerSilently """
        try:
            if not self.monitoredPlayers.containsKey(hostport):
                self.monitoredPlayers.put(hostport, presence)
                return presence
            else:
                return self.monitoredPlayers.get(hostport)
        except ArrayIndexOutOfBoundsException as e:
            raise self.InvalidHostportException()
        except NumberFormatException as e:
            raise self.InvalidHostportException()

    def addPlayer(self, hostport):
        """ generated source for method addPlayer """
        presence = self.addPlayerSilently(hostport)
        notifyObservers(self.PlayerPresenceAdded())
        savePlayersJSON()
        return presence

    def removePlayer(self, hostport):
        """ generated source for method removePlayer """
        self.monitoredPlayers.remove(hostport)
        notifyObservers(self.PlayerPresenceRemoved())
        savePlayersJSON()

    def getPresence(self, hostport):
        """ generated source for method getPresence """
        return self.monitoredPlayers.get(hostport)

    def getSortedPlayerNames(self):
        """ generated source for method getSortedPlayerNames """
        return TreeSet(self.monitoredPlayers.keySet())

    observers = HashSet()

    def addObserver(self, observer):
        """ generated source for method addObserver """
        self.observers.add(observer)

    def notifyObservers(self, event):
        """ generated source for method notifyObservers """
        for observer in observers:
            observer.observe(event)

    playerListFilename = ".ggpserver-playerlist.json"

    def savePlayersJSON(self):
        """ generated source for method savePlayersJSON """
        try:
            playerListJSON.put("hostports", self.monitoredPlayers.keySet())
            if not file_.exists():
                file_.createNewFile()
            bw.write(playerListJSON.__str__())
            bw.close()
        except IOException as ie:
            ie.printStackTrace()
        except JSONException as e:
            e.printStackTrace()

    def loadPlayersJSON(self):
        """ generated source for method loadPlayersJSON """
        try:
            if not file_.exists():
                return
            try:
                while (line = br.readLine()) != None:
                    pdata.append(line)
            finally:
                br.close()
            if playerListJSON.has("hostports"):
                while i < len(theHostports):
                    try:
                        self.addPlayerSilently(theHostports.get(i).__str__())
                    except InvalidHostportException as e:
                        e.printStackTrace()
                    i += 1
        except IOException as ie:
            ie.printStackTrace()
        except JSONException as e:
            e.printStackTrace()
Esempio n. 21
0
class TimerTab(ITab, IHttpListener):
    def __init__(self, callbacks, helpers):
        self._callbacks = callbacks
        self._helpers = helpers
        self.isRunning = True
        self.toolFilter = 0
        self.reqResMap = HashMap()
        callbacks.registerHttpListener(self)
        self.panel = TimerPanel(
            logtable_factory=lambda model: LogTable(model, self._callbacks),
            external_clear_button_action_listener=lambda e: self.getReqResMap(
            ).clear(),
            external_start_button_action_listener=lambda e: self.setRunning(
                True),
            external_stop_button_action_listener=lambda e: self.setRunning(
                False),
            external_filter_action_listener=self.filter_action_listener,
            tools_keys=["All", "Proxy", "Intruder", "Scanner", "Repeater"])

    def getTabCaption(self):
        """
        Override ITab method
        :return: tab name
        """
        return "InQL Timer"

    def getUiComponent(self):
        """
        Override ITab method
        :return: Tab UI Component
        """
        self._callbacks.customizeUiComponent(self.panel.this)
        return self.panel.this

    def filter_action_listener(self, e):
        tool = e.getSource().getSelectedItem()
        if tool == "All":
            self.setToolFilter(0)
        elif tool == "Proxy":
            self.setToolFilter(IBurpExtenderCallbacks.TOOL_PROXY)
        elif tool == "Intruder":
            self.setToolFilter(IBurpExtenderCallbacks.TOOL_INTRUDER)
        elif tool == "Scanner":
            self.setToolFilter(IBurpExtenderCallbacks.TOOL_SCANNER)
        elif tool == "Repeater":
            self.setToolFilter(IBurpExtenderCallbacks.TOOL_REPEATER)
        else:
            raise RuntimeError("Unknown tool: %s" % tool)

    def setRunning(self, running):
        self.isRunning = running

    def setToolFilter(self, toolFilter):
        self.toolFilter = toolFilter

    def processHttpMessage(self, toolFlag, messageIsRequest, requestResponse):

        if self.isRunning:
            if self.toolFilter == 0 or self.toolFilter == toolFlag:
                messageInfo = self._helpers.analyzeRequest(requestResponse)
                url = messageInfo.getUrl()
                requestBody = requestResponse.getRequest(
                )[messageInfo.getBodyOffset():].tostring()
                if not is_query(requestBody):
                    return  # exit early
                qobj = json.loads(requestBody)
                queryBody = ""
                operationName = ""
                if 'query' in qobj:
                    queryBody = qobj['query']
                if 'operationName' in qobj:
                    operationName = qobj['operationName']
                if messageIsRequest:
                    self.reqResMap.put(url, System.currentTimeMillis())
                elif self.reqResMap.containsKey(url):
                    time = System.currentTimeMillis() - self.reqResMap.get(url)
                    self.reqResMap.remove(url)
                    # create a new log entry with the message details
                    synchronize.apply_synchronized(
                        self.panel.getLogTableModel().getLogArray(),
                        self.syncProcessHttpMessage,
                        (toolFlag, requestResponse, time, queryBody,
                         operationName))

    def syncProcessHttpMessage(self, toolFlag, messageInfo, time, queryBody,
                               operationName):
        row = self.panel.getLogTableModel().getLogArray().size()
        # Log all requests - the default
        if not self.panel.getQueryFilterText(
        ) and not self.panel.isScopeSelected():
            self.addLog(messageInfo, toolFlag, time, row, operationName)
        # Log filter URL requests
        elif not self.panel.isScopeSelected() and self.panel.getQueryFilterText() and \
            self.panel.getQueryFilterText() in queryBody:
            self.addLog(messageInfo, toolFlag, time, row, operationName)
        # Log in-scope requests
        elif self.panel.isScopeSelected() and not self.panel.getQueryFilterText() and \
              self._callbacks.isInScope(self._helpers.analyzeRequest(messageInfo).getUrl()):
            self.addLog(messageInfo, toolFlag, time, row, operationName)
        # Log in-scope requests and filter
        elif self.panel.isScopeSelected() and self.panel.getQueryFilterText() and \
                self._callbacks.isInScope(self._helpers.analyzeRequest(messageInfo).getUrl()) and \
                self.panel.getQueryFilterText() in queryBody:
            self.addLog(messageInfo, toolFlag, time, row, operationName)

    def addLog(self, messageInfo, toolFlag, time, row, operationName):

        self.panel.getLogTableModel().getLogArray().add(
            Log(
                LocalDateTime.now(), self._callbacks.getToolName(toolFlag),
                self._callbacks.saveBuffersToTempFiles(messageInfo),
                self._helpers.analyzeRequest(messageInfo).getUrl(),
                self._helpers.analyzeResponse(
                    messageInfo.getResponse()).getStatusCode(), operationName,
                time))
        self.panel.getLogTableModel().fireTableRowsInserted(row, row)

    def getReqResMap(self):
        return self.reqResMap
Esempio n. 22
0
class TtlCache(Map, K, V):
    """ generated source for class TtlCache """
    class Entry(object):
        """ generated source for class Entry """
        ttl = int()
        value = V()

        def __init__(self, value, ttl):
            """ generated source for method __init__ """
            self.value = value
            self.ttl = ttl

        @SuppressWarnings("unchecked")
        def equals(self, o):
            """ generated source for method equals """
            if isinstance(o, (self.Entry, )):
                return (o).value == self.value
            return False

    contents = Map()
    ttl = int()

    def __init__(self, ttl):
        """ generated source for method __init__ """
        super(TtlCache, self).__init__()
        self.contents = HashMap()
        self.ttl = ttl

    @synchronized
    def containsKey(self, key):
        """ generated source for method containsKey """
        return self.contents.containsKey(key)

    @synchronized
    def get(self, key):
        """ generated source for method get """
        entry = self.contents.get(key)
        if entry == None:
            return None
        #  Reset the TTL when a value is accessed directly.
        entry.ttl = self.ttl
        return entry.value

    @synchronized
    def prune(self):
        """ generated source for method prune """
        toPrune = ArrayList()
        for key in contents.keySet():
            if entry.ttl == 0:
                toPrune.add(key)
            entry.ttl -= 1
        for key in toPrune:
            self.contents.remove(key)

    @synchronized
    def put(self, key, value):
        """ generated source for method put """
        x = self.contents.put(key, self.Entry(value, self.ttl))
        if x == None:
            return None
        return x.value

    @synchronized
    def size(self):
        """ generated source for method size """
        return len(self.contents)

    @synchronized
    def clear(self):
        """ generated source for method clear """
        self.contents.clear()

    @synchronized
    def containsValue(self, value):
        """ generated source for method containsValue """
        return self.contents.containsValue(value)

    @synchronized
    def isEmpty(self):
        """ generated source for method isEmpty """
        return self.contents.isEmpty()

    @synchronized
    def keySet(self):
        """ generated source for method keySet """
        return self.contents.keySet()

    @synchronized
    def putAll(self, m):
        """ generated source for method putAll """
        for anEntry in m.entrySet():
            self.put(anEntry.getKey(), anEntry.getValue())

    @synchronized
    def remove(self, key):
        """ generated source for method remove """
        return self.contents.remove(key).value

    @synchronized
    def values(self):
        """ generated source for method values """
        theValues = HashSet()
        for e in contents.values():
            theValues.add(e.value)
        return theValues

    class entrySetMapEntry(Map, Entry, K, V):
        """ generated source for class entrySetMapEntry """
        key = K()
        value = V()

        def __init__(self, k, v):
            """ generated source for method __init__ """
            super(entrySetMapEntry, self).__init__()
            self.key = k
            self.value = v

        def getKey(self):
            """ generated source for method getKey """
            return self.key

        def getValue(self):
            """ generated source for method getValue """
            return self.value

        def setValue(self, value):
            """ generated source for method setValue """
            return (self.value = value)

    @synchronized
    def entrySet(self):
        """ generated source for method entrySet """
        theEntries = HashSet()
        for e in contents.entrySet():
            theEntries.add(self.entrySetMapEntry(e.getKey(), e.getValue().value))
        return theEntries