예제 #1
0
	def addBuild(self, data, channel, jarname):
		fileName = self.download_file(data, self.channelModes[channel])
		modifier = Modifier(jarname)
		modifier.modify(fileName, data)

		if not 'checksum' in data or not data['checksum']:
			data['checksum'] = self.md5sumLocal(fileName)

		if not channel in self.channels:
			raise Exception('Tried to add a build %s in a nonexistant channel %s.' % (data['build'], channel))
		if not data['version'] in self.versions:
			version = self.addVersion(data['version'], channel)
		else:
			version = self.versions[data['version']]

		del data['version']
		data['version_id'] = version

		self.getOrMake(model = Build, data = data, where = { 'build': data['build'], 'version_id': data['version_id'] })
		self.bubbleUpdate(version);
예제 #2
0
    def add(self, **raw_mod):
        """Add a modifier to the modifier handler. 

        Arguments:
        raw_mod (kwargs) - constructor arguments for Modifier

        Returns: None
        """
        mod_desc = raw_mod["desc"]
        if not self.modifiers.get(mod_desc):
            self.modifiers[mod_desc] = []
        new_mod = Modifier.factory(**raw_mod)
        self.modifiers[mod_desc].append(new_mod)
        self._raw_modifiers.append(new_mod)
예제 #3
0
    def addBuild(self, data, channel, jarname):
        modifier = Modifier(jarname)
        if (('checksum' not in data or not data['checksum']
                or modifier.isNeeded() or 'size' not in data
                or not data['size'] or self.config['CACHE_ALWAYS'])
                and not self.config['NEVER_DOWNLOAD']):
            fileName = self.download_file(data)

            try:
                modifier.modify(fileName, data)

                if 'checksum' not in data or not data['checksum']:
                    data['checksum'] = self.md5sumLocal(fileName)
                if 'size' not in data or not data['size']:
                    data['size'] = os.path.getsize(fileName)
            finally:
                if (not (self.config['CACHE_PATCHED'] and modifier.isNeeded())
                        or self.config['CACHE_ALWAYS']):
                    os.remove(fileName)

        if channel not in self.channels:
            raise Exception(
                'Tried to add a build {} in a nonexistant channel {}.'.format(
                    data['build'], channel))
        if data['version'] not in self.versions:
            version = self.addVersion(data['version'], channel)
        else:
            version = self.versions[data['version']]

        del data['version']
        data['version_id'] = version

        self.getOrMake(model=Build, data=data,
                       where={'build': data['build'],
                              'version_id': data['version_id']})
        self.bubbleUpdate(version)
예제 #4
0
 def candyxml_create(cls, element):
     """
     Parse the candyxml element for parameter and create a Template.
     """
     modifier = []
     for subelement in element.get_children():
         mod = Modifier.candyxml_create(subelement)
         if mod is not None:
             modifier.append(mod)
             element.remove(subelement)
     widget = cls.candyxml_get_class(element)
     if widget is None:
         log.error('undefined widget %s:%s', element.node, element.style)
     kwargs = widget.candyxml_parse(element)
     if modifier:
         kwargs['modifier'] = modifier
     template = cls(widget, name=kwargs.candyname, **kwargs)
     return template
예제 #5
0
 def candyxml_create(cls, element):
     """
     Parse the candyxml element for parameter and create a Template.
     """
     modifier = []
     for subelement in element.get_children():
         mod = Modifier.candyxml_create(subelement)
         if mod is not None:
             modifier.append(mod)
             element.remove(subelement)
     widget = cls.candyxml_get_class(element)
     if widget is None:
         log.error('undefined widget %s:%s', element.node, element.style)
     kwargs = widget.candyxml_parse(element)
     if modifier:
         kwargs['modifier'] = modifier
     template = cls(widget, name=kwargs.candyname, **kwargs)
     return template
예제 #6
0
def main():
    parser = argparse.ArgumentParser(description='IpaModifier')
    parser.add_argument('ipa', type=str, help='IPA File (*.ipa)')
    parser.add_argument('config', type=str, help='Config file (*.json)')

    # Parse arguments.
    args = parser.parse_args()

    if not args.ipa or not args.config:
        parser.print_help()
        return False

    if not os.path.exists(args.ipa):
        print('IPA file was not found.')
        return False

    if not os.path.exists(args.config):
        print('Config file was not found.')
        return False

    with Modifier(args.ipa, args.config) as modifier:
        return modifier.modify()
예제 #7
0
 def add_modifier(self, adjective):
     modifier_id = self.vocabulary.register_adjective(Modifier(self.game, name=adjective))
     self.modifiers.add(modifier_id)
예제 #8
0
    def __init__(self, meta_info):
        self.meta_info = meta_info

        self.identifier = Identifier(self.meta_info)
        self.modifier = Modifier(self.identifier)
예제 #9
0
class Copier:
    def __init__(self, meta_info):
        self.meta_info = meta_info

        self.identifier = Identifier(self.meta_info)
        self.modifier = Modifier(self.identifier)

    ###############################################################################################
    # Main
    ###############################################################################################
    # TODO delete
    # def run2(self):
    #     # https://www.machinelearningplus.com/python/cprofile-how-to-profile-your-python-code/
    #     import cProfile, pstats
    #     profiler = cProfile.Profile()
    #     profiler.enable()
    #     self.run2()
    #     profiler.disable()
    #     stats = pstats.Stats(profiler).sort_stats("tottime")
    #     stats.print_stats()
    #     #import cProfile
    #     #cProfile.run("self.run2()")

    def run(self):
        self.air_pockets = self.meta_info.air_pockets.get()
        self.water_blocks = self.meta_info.water_blocks.get()
        self.repl_blocks = self.meta_info.repl_blocks.get()

        # Print detailed informations
        # TODO improve
        if self.air_pockets == 1:
            self.meta_info.text_queue.put("Air Blocks will be fixed!\n")
        else:
            self.meta_info.text_queue.put("Air Blocks will not be fixed!\n")

        if self.water_blocks == 1:
            self.meta_info.text_queue.put("Water Blocks will be fixed!\n")
        else:
            self.meta_info.text_queue.put("Water Blocks will not be fixed!\n")

        if self.repl_blocks == 1:
            self.meta_info.text_queue.put(
                "Replacement Blocks will be inserted!\n")
        else:
            self.meta_info.text_queue.put(
                "Replacement Blocks will not be inserted!\n")

        self.meta_info.text_queue.put("\n.. starting\n")
        t1 = gmtime()
        self.meta_info.text_queue.put(strftime("%Y-%m-%d %H:%M:%S\n", t1))
        ms = int(round(time.time() * 1000))

        # Get all files in the directory
        src_dir = self.meta_info.source_dir.get()
        filelist = None
        if os.path.exists(src_dir):
            filelist = os.listdir(src_dir)

        if filelist is None or len(filelist) == 0:
            messagebox.showinfo(
                message="No files found! Select a different source path.",
                title="Error")
            return

        tgt_dir = self.meta_info.target_dir.get()
        try:
            if not os.path.exists(tgt_dir):
                os.mkdir(tgt_dir)
        except OSError:
            messagebox.showinfo(message="Creation of the directory %s failed" %
                                tgt_dir,
                                title="Error")

        # Update the progressbar and label for the files
        self.meta_info.file_count_max = len(filelist)

        # Iterate the files
        i = 1
        for filename in filelist:
            if filename.endswith(".mca"):
                # TODO combine path and filename here ?
                self.copyRegion(filename)
            else:
                continue
            self.meta_info.file_count = i
            i += 1

        # Print that the process is finished
        self.meta_info.text_queue.put("\n.. finished\n")
        t2 = gmtime()
        self.meta_info.text_queue.put(strftime("%Y-%m-%d %H:%M:%S\n", t2))
        self.meta_info.text_queue.put("Total runtime: ")
        self.meta_info.text_queue.put(
            datetime.timedelta(seconds=time.mktime(t2) - time.mktime(t1)))

        ms2 = int(round(time.time() * 1000))
        print(f"Total time elapsed: {ms2 - ms}")

        self.meta_info.finished = True

    ###############################################################################################

    def copyRegion(self, filename):
        end = filename.split(".")
        rX = int(end[1])
        rZ = int(end[2])

        # Create a new region with the `EmptyRegion` class at region coords
        new_region = anvil.EmptyRegion(rX, rZ)
        src_dir = self.meta_info.source_dir.get()
        region = anvil.Region.from_file(src_dir + "/" + filename)

        repl_region = False
        if self.repl_blocks:
            try:
                repl_dir = self.meta_info.replacement_dir.get()
                repl_region = anvil.Region.from_file(repl_dir + "/" + filename)
            except Exception:
                print(f"Could not create replacement region for {filename}.")

        ##########################################
        # Main function call
        ##########################################
        self.copy_chunks(new_region, region, repl_region)

        if self.water_blocks + self.air_pockets + self.repl_blocks >= 1:
            self.meta_info.text_queue.put(f"In file {filename}:\n")
        if self.air_pockets == 1:
            self.meta_info.text_queue.put(
                f"Changed {self.meta_info.counts.changed_air.value} air blocks to solid blocks.\n"
            )
        if self.water_blocks == 1:
            self.meta_info.text_queue.put(
                f"Changed {self.meta_info.counts.changed_water.value} solid blocks to water.\n"
            )
        if self.repl_blocks == 1:
            self.meta_info.text_queue.put(
                f"Changed {self.meta_info.counts.changed_repl.value} "
                "solid blocks to replacement solid blocks.\n")

        ms = int(round(time.time() * 1000))

        ##########################################
        # Other modifications
        ##########################################
        # if self.meta_info.make_tunnel()
        # self.modifier.make_tunnel(
        #     region, new_region, rX, rZ,
        #     self.meta_info.get_tunnel_start(), self.meta_info.get_tunnel_end()
        # )
        # self.modifier.make_tunnel(region, new_region, rX, rZ, [125, 80, 100], [125, 80, 350])
        # self.modifier.make_tunnel(region, new_region, rX, rZ, [125, 60, 100], [225, 60, 350])
        # self.modifier.make_tunnel(region, new_region, rX, rZ, [125, 100, 100], [325, 100, 250])

        ms2 = int(round(time.time() * 1000))
        print(f"Tunnel time: {ms2 - ms}")

        # Save to a file
        self.meta_info.counts.algo_step = cfg.A_SAVE
        target_dir = self.meta_info.target_dir.get()
        new_region.save(target_dir + "/" + filename, region)
        self.meta_info.counts.algo_step = cfg.A_FINISHED

        ms = int(round(time.time() * 1000))
        print(f"Save time: {ms - ms2}")

    ###############################################################################################

    def copy_chunks(self, new_region, region, repl_region):
        ms = int(round(time.time() * 1000))

        # TODO combine these into a function?
        self.meta_info.counts.algo_step = cfg.A_CLASSIFY
        self.meta_info.counts.chunks_c.value = 0
        classifier_mp = ClassifierMP(self.meta_info)
        if self.air_pockets + self.repl_blocks + self.water_blocks > 0:
            classifier_mp.classify_all_mp(region, self.meta_info.counts,
                                          self.meta_info.timer)

        ms2 = int(round(time.time() * 1000))
        print(f"Classifier time: {ms2 - ms}")

        self.meta_info.counts.algo_step = cfg.A_IDENTIFY
        self.identifier.identify(classifier_mp.c_regions,
                                 self.meta_info.counts, self.meta_info.timer)

        ms3 = int(round(time.time() * 1000))
        print(f"Identifier time: {ms3 - ms2}")

        self.meta_info.counts.algo_step = cfg.A_MODIFY
        self.meta_info.counts.chunks_m.value = 0
        for chunk_x in range(cfg.REGION_C_X):

            self.meta_info.timer.start_time()
            for chunk_z in range(cfg.REGION_C_Z):
                self.copy_chunk(new_region, region, repl_region, chunk_x,
                                chunk_z)
                self.meta_info.counts.chunks_m.value += 1

            self.meta_info.timer.end_time()
            self.meta_info.timer.update_m_elapsed(self.meta_info.counts)

        ms4 = int(round(time.time() * 1000))
        print(f"Modify time: {ms4 - ms3}")

    ###############################################################################################

    def copy_chunk(self, new_region, region, repl_region, chunk_x, chunk_z):
        chunk = None
        try:
            chunk = anvil.Chunk.from_region(region, chunk_x, chunk_z)
        except Exception:
            print(f"skipped non-existent chunk ({chunk_x},{chunk_z})")

        if chunk:
            # TODO only when the option is ticked?
            repl_chunk = False
            if repl_region:
                try:
                    repl_chunk = anvil.Chunk.from_region(
                        repl_region, chunk_x, chunk_z)
                except Exception:
                    print(
                        f"Could not create replacement chunk for {chunk_x}, {chunk_z}."
                    )

            self.modifier.modify(chunk, repl_chunk, new_region, chunk_x,
                                 chunk_z)
예제 #10
0
 def identify(str0: str) -> PartSum:
     #split input
     parts = UserInterface.splitParts(str0)
     part_list = []
     #validate input
     for part in parts:
         if part.count(Dice.SEP) > 1:
             raise ValueError(
                 'Must be at most 1 dice separator in a roll part!')
         if part.count(Dice.RANGE_START) > 1:
             raise ValueError(
                 'Must be at most 1 dice range starter in a roll part!')
         if part.count(Dice.RANGE_END) > 1:
             raise ValueError(
                 'Must be at most 1 dice range ender in a roll part!')
         if part.count(Dice.RANGE_START) != part.count(Dice.RANGE_END):
             raise ValueError(
                 'Must be the same number of dice range starters and enders in a roll part!'
             )
         if part.find(Dice.RANGE_START) > part.find(Dice.RANGE_END):
             raise ValueError(
                 'A dice range starter must come before a dice range ender in a roll part!'
             )
         if part.count(Dice.DROP_HIGH) > 1:
             raise ValueError(
                 'Must be at most 1 drop high flag in a roll part!')
         if part.count(Dice.DROP_LOW) > 1:
             raise ValueError(
                 'Must be at most 1 drop low flag in a roll part!')
         if part.find(Dice.DROP_HIGH) != -1 and part.find(
                 Dice.DROP_LOW) != -1:
             raise ValueError(
                 'Cannot have both a drop high and a drop low flag in a roll part!'
             )
         if part.find(Dice.DROP_HIGH) != -1 and part.find(
                 Dice.DROP_HIGH) + len(Dice.DROP_HIGH) != part.find(
                     Dice.SEP):
             raise ValueError(
                 'A drop high flag must come immediately before a dice separator in a roll part!'
             )
         if part.find(Dice.DROP_LOW) != -1 and part.find(
                 Dice.DROP_LOW) + len(Dice.DROP_LOW) != part.find(Dice.SEP):
             raise ValueError(
                 'A drop low flag must com immediately before a dice separator in a roll part!'
             )
         #interpret input
         if part.count(Dice.SEP) == 1:
             lhs = part.partition(Dice.SEP)[0]
             rhs = part.partition(Dice.SEP)[2]
             if lhs.find(Dice.DROP_HIGH) != -1:
                 drop = 1
                 lhs = lhs[:-len(Dice.DROP_LOW)]
             elif lhs.find(Dice.DROP_LOW) != -1:
                 drop = -1
                 lhs = lhs[:-len(Dice.DROP_LOW)]
             else:
                 drop = 0
             if rhs == Dice.FUDGE:
                 faces = Dice.FUDGE_RANGE
                 if lhs[0] == RollPart.NEG:
                     lhs = lhs[1:]
             elif rhs[0] == Dice.RANGE_START and rhs[-1] == Dice.RANGE_END:
                 faces = rhs.strip(Dice.RANGE_START + Dice.RANGE_END).split(
                     Dice.RANGE_SEP)
                 for i in range(len(faces)):
                     faces[i] = int(faces[i])
             else:
                 faces = int(rhs)
             if int(lhs) < 0:
                 if isinstance(faces, list):
                     faces.reverse()
                     for i in range(len(faces)):
                         faces[i] *= -1
                 elif isinstance(faces, int):
                     faces *= -1
                 else:
                     raise TypeError('Unexpected \'faces\' type ' +
                                     repr(type(faces)))
             dice = Dice(abs(int(lhs)), faces, drop)
             part_list.append(Dice(abs(int(lhs)), faces, drop))
         else:
             part_list.append(Modifier(int(part)))
     return PartSum(part_list)
예제 #11
0
                break
            end = string[start:].index(PartSum.GROUP_END) + start
            if string[start:end + 1].count(RollPart.POS) < 1:
                string = string[:start] + string[start + 1:end] + string[end +
                                                                         1:]
            i = end + 1
        string += PartSum.PART_SEP + PartSum.RES_SEP + PartSum.PART_SEP + str(
            parts[1])
        return string

    def min_str(self) -> str:
        return self.string(self.min())

    def max_str(self) -> str:
        return self.string(self.max())

    def avg_str(self) -> str:
        return self.string(self.avg())

    def rand_str(self) -> str:
        return self.string(self.rand())


assert PartSum([Dice(2, 6), Modifier(2)]) == PartSum([Dice(2, 6), Modifier(2)])
assert PartSum([Dice(2, 6), Modifier(2)]).min() == ([[1, 1], [2]], 4)
assert PartSum([Dice(2, 6), Modifier(2)]).max() == ([[6, 6], [2]], 14)
assert PartSum([Dice(2, 6), Modifier(2)]).avg() == ([[3.5, 3.5], [2]], 9.0)
assert PartSum([Dice(2, 6), Modifier(2)]).min_str() == '(1 + 1) + 2 = 4'
assert PartSum([Dice(2, 6), Modifier(2)]).max_str() == '(6 + 6) + 2 = 14'
assert PartSum([Dice(2, 6), Modifier(2)]).avg_str() == '(3.5 + 3.5) + 2 = 9.0'
	print "Final location:", goalState.loc['me']
	print "Final cash:", goalState.cash['me']	
	print
		
	# Use the Retreiver module to get a closed match case
	# The returning case has source state, dest state and executed plan 
	retrievedCase = rt.findClosestMatch(currentState, goalState)
	
	
	if len(retrievedCase) > 0:		
		# Get the plan part of the case
		retrievedPlan = retrievedCase[1]
		print 'Retrieved plan:', retrievedPlan
	else:
		print 'No match found'
	print
		
	# Create the Modifier module, given the problem domain related info file 
	modifier = Modifier('state_similarity.txt')
	
	# Use the Modifier module to get a modified plan
	# Current state, goal state and the retrieved case(with source state, dest state, plan) is passed
	modifiedPlan, successFlag = modifier.modifyPlan(currentState, goalState, retrievedCase)
	
	# We see whether the modifier could modify to a better plan
	if successFlag == True:
		print "Modified Plan:", modifiedPlan
	else:
		# Modifier could not fully modify the plan to match our goal state, partially modified plan
		# is shown here
		print "Closest Plan found:", modifiedPlan
예제 #13
0
    def morph_image(self, aligned_face):
        height, width, _ = self.image.shape
        face = aligned_face.face.copy()
        
        face.realign_into_bounding_box(aligned_face.face_bounding_box, width, height)
        return face.morph_with(self.image, aligned_face.face_bounding_box.size)

    def plot(self, plt):
        plt.imshow(self.image)

        for face in self.faces:
            plt.scatter(*face.landmarks.T, marker='.')
            face.aligned_face.plot(plt)

if __name__ == "__main__":
    transformer = FaceTransformer()
    transformer.detect_faces('./images/000055.jpg')

    aligned_face = transformer.faces[0]

    modifier = Modifier(aligned_face.face, attribute='Smiling', i=5)
    modifier.addExpression(3)
    aligned_face.face = modifier.decode_face()

    aligned_face.plot(plt)
    plt.show()

    img = transformer.morph_image(aligned_face)

    image = Image.fromarray(np.uint8(img * 255))
    image.show()