def matchmaker():
    guysfree = guys[:]
    engaged = dict((she, []) for she in gals)
    guyprefers2 = copy.deepcopy(guyprefers)
    galprefers2 = copy.deepcopy(galprefers)
    while guysfree:
        guy = guysfree.pop(0)
        guyslist = guyprefers2[guy]
        gal = guyslist.pop(0)
        fiances = engaged.get(gal)
        if len(fiances) < capacity[gal]:
            # She still has places
            engaged[gal].append(guy)
            engaged[gal] = orderlist(gal, engaged[gal])
            print("  %s and %s" % (guy, gal))
        else:
            # The bounder proposes to an engaged lass!
            lastfiance = engaged[gal][-1]
            galslist = galprefers2[gal]
            if galslist.index(lastfiance) > galslist.index(guy):
                # She prefers new guy
                del engaged[gal][-1]
                # Remove lastfiance
                engaged[gal].append(guy)
                engaged[gal] = orderlist(gal, engaged[gal])
                print("  %s dumped %s for %s" % (gal, lastfiance, guy))
                if guyprefers2[lastfiance]:
                    # Ex has more girls to try
                    guysfree.append(lastfiance)
            else:
                # She is faithful to old fiance
                if guyslist:
                    # Look again
                    guysfree.append(guy)
    return engaged
Beispiel #2
1
Datei: vqa.py Projekt: tylin/VQA
    def loadRes(self, resFile):
        """
		Load result file and return a result object.
		:param   resFile (str)     : file name of result file
		:return: res (obj)         : result api object
		"""
        res = VQA()
        res.dataset["info"] = copy.deepcopy(self.dataset["info"])
        res.dataset["task_type"] = copy.deepcopy(self.dataset["task_type"])
        res.dataset["data_type"] = copy.deepcopy(self.dataset["data_type"])
        res.dataset["data_subtype"] = copy.deepcopy(self.dataset["data_subtype"])
        res.dataset["license"] = copy.deepcopy(self.dataset["license"])

        print "Loading and preparing results...     "
        time_t = datetime.datetime.utcnow()
        anns = json.load(open(resFile))
        assert type(anns) == list, "results in not an array of objects"
        annsQuesIds = [ann["question_id"] for ann in anns]
        assert set(annsQuesIds) == (
            set(annsQuesIds) & set(self.getQuesIds())
        ), "Results do not correspond to current VQA set"
        for ann in anns:
            quesId = ann["question_id"]
            qaAnn = self.qa[quesId]
            ann["image_id"] = qaAnn["image_id"]
            ann["question"] = qaAnn["question"]
            ann["question_type"] = qaAnn["question_type"]
            ann["answer_type"] = qaAnn["answer_type"]
        print "DONE (t=%0.2fs)" % ((datetime.datetime.utcnow() - time_t).total_seconds())

        res.dataset["annotations"] = anns
        res.createIndex()
        return res
Beispiel #3
1
    def add_page(self, page):
        """ Spread only manage 2 pages. """
        if self.pages:
            # the last page is also the first (and only) one here and is a verso (front).
            face_required = RECTO
            last_page = self.pages[-1]
            last_page.node.addnext(copy.deepcopy(page.node))
        else:
            face_required = VERSO
            self.node.append(copy.deepcopy(page.node))
        # TODO: attributes (layer, masterSpread, ...)
        for item in page.page_items:
            self.node.append(copy.deepcopy(item))
        self._pages = None

        # Correct the position of the new page in the Spread.
        last_page = self.pages[-1]

        # At this level, because the last_page may not be in a correct position
        # into the Spread, a call to last_page.page_items may also return
        # the page items of the other page of the Spread.
        # So we force the setting from the inserted page and use those references
        # to move the items if the face has to be changed.
        items_references = [item.get("Self") for item in page.page_items]
        last_page.page_items = [item for item in last_page.page_items if item.get("Self") in items_references]
        last_page.set_face(face_required)
Beispiel #4
1
    def test_format_selection_audio_exts(self):
        formats = [
            {"format_id": "mp3-64", "ext": "mp3", "abr": 64, "url": "http://_", "vcodec": "none"},
            {"format_id": "ogg-64", "ext": "ogg", "abr": 64, "url": "http://_", "vcodec": "none"},
            {"format_id": "aac-64", "ext": "aac", "abr": 64, "url": "http://_", "vcodec": "none"},
            {"format_id": "mp3-32", "ext": "mp3", "abr": 32, "url": "http://_", "vcodec": "none"},
            {"format_id": "aac-32", "ext": "aac", "abr": 32, "url": "http://_", "vcodec": "none"},
        ]

        info_dict = _make_result(formats)
        ydl = YDL({"format": "best"})
        ie = YoutubeIE(ydl)
        ie._sort_formats(info_dict["formats"])
        ydl.process_ie_result(copy.deepcopy(info_dict))
        downloaded = ydl.downloaded_info_dicts[0]
        self.assertEqual(downloaded["format_id"], "aac-64")

        ydl = YDL({"format": "mp3"})
        ie = YoutubeIE(ydl)
        ie._sort_formats(info_dict["formats"])
        ydl.process_ie_result(copy.deepcopy(info_dict))
        downloaded = ydl.downloaded_info_dicts[0]
        self.assertEqual(downloaded["format_id"], "mp3-64")

        ydl = YDL({"prefer_free_formats": True})
        ie = YoutubeIE(ydl)
        ie._sort_formats(info_dict["formats"])
        ydl.process_ie_result(copy.deepcopy(info_dict))
        downloaded = ydl.downloaded_info_dicts[0]
        self.assertEqual(downloaded["format_id"], "ogg-64")
Beispiel #5
1
    def to_orange_network(self):
        """Convert the current network to >>Orange<< NetworkX standard. To use
        :obj:`Orange.network` in Orange widgets, set node IDs to be range 
        [0, no_of_nodes - 1].
        
        """

        G = self.__class__()
        node_list = sorted(self.nodes())
        node_to_index = dict(zip(node_list, range(self.number_of_nodes())))
        index_to_node = dict(zip(range(self.number_of_nodes()), node_list))

        G.add_nodes_from(zip(range(self.number_of_nodes()), [copy.deepcopy(self.node[nid]) for nid in node_list]))
        G.add_edges_from(
            ((node_to_index[u], node_to_index[v], copy.deepcopy(self.edge[u][v])) for u, v in self.edges())
        )

        for id in G.node.keys():
            G.node[id]["old_id"] = index_to_node[id]

        if self.items():
            G.set_items(self.items())

        if self.links():
            G.set_links(self.links())

        return G
        def comp(data, expected):
            # First socorrodotdict_to_dict the data and compare it.
            new_dict = socorrodotdict_to_dict(data)
            eq_(new_dict, expected)

            # Now deepcopy the new dict to make sure it's ok.
            copy.deepcopy(new_dict)
Beispiel #7
0
def decode(key, value):
    if isinstance(value, get_dumpable_types()):
        return value

    if isinstance(value, (tuple, list)):
        return [decode(key, x) for x in value]

    if not isinstance(value, dict):
        return value

    if "__type" not in value:
        return dict([(k, decode(k, v)) for k, v in value.iteritems()])

    _type = value["__type"]

    if _type == "Pointer":
        value = copy.deepcopy(value)
        class_name = value["className"]
        pointer = leancloud.Object.create(class_name)
        if "createdAt" in value:
            value.pop("__type")
            value.pop("className")
            pointer._finish_fetch(value, True)
        else:
            pointer._finish_fetch({"objectId": value["objectId"]}, False)
        return pointer

    if _type == "Object":
        value = copy.deepcopy(value)
        class_name = value["className"]
        value.pop("__type")
        value.pop("class_name")
        obj = leancloud.Object.create(class_name)
        obj._finish_fetch(value, True)
        return obj

    if _type == "Date":
        return arrow.get(iso8601.parse_date(value["iso"])).to("local").datetime

    if _type == "GeoPoint":
        return leancloud.GeoPoint(latitude=value["latitude"], longitude=value["longitude"])

    if key == "ACL":
        if isinstance(value, leancloud.ACL):
            return value
        return leancloud.ACL(value)

    if _type == "Relation":
        relation = leancloud.Relation(None, key)
        relation.target_class_name = value["className"]
        return relation

    if _type == "File":
        f = leancloud.File(value["name"])
        meta_data = value.get("metaData")
        if meta_data:
            f._metadata = meta_data
        f._url = value["url"]
        f.id = value["objectId"]
        return f
Beispiel #8
0
def merge_dict_from_to(d1, d2):
    """Merges dictionary d1 into dictionary d2. d1 will remain in original form."""
    import copy

    for k, v in d1.items():
        if k in d2:
            if type(v) == type(d2[k]):
                if isinstance(v, dict):
                    merge_dict_from_to(d1[k], d2[k])
                elif isinstance(v, list):
                    d2[k].extend(copy.deepcopy(v))
                elif isinstance(v, basestring) or isinstance(v, bool) or isinstance(v, int) or isinstance(v, float):
                    pass
                else:
                    raise Exception("Unknown type: %s value: %s in dictionary" % (type(v), repr(v)))
            elif isinstance(v, basestring) and isinstance(d2[k], basestring):
                # Strings are compatible by definition
                # (though we could get a decode error later, this is higly unlikely for config values)
                pass
            else:
                raise MergeException(
                    "Merging key %s failed, conflicting datatypes %r vs. %r."
                    % (k, type(v).__name__, type(d2[k]).__name__)
                )
        else:
            d2[k] = copy.deepcopy(v)
Beispiel #9
0
 def test(case):
     assert len(self.funcs) > 0
     for i in range(len(case)):
         ret = self.funcs[0](copy.deepcopy(case), i)
         assert all(f(copy.deepcopy(case), i) == ret for f in self.funcs[1:])
     ret = self._traverse(copy.deepcopy(case), self.funcs[0])
     assert all(self._traverse(copy.deepcopy(case), f) == ret for f in self.funcs[1:])
Beispiel #10
0
 def CombinePattern(self, PatternA, PatternB):
     PatA1 = PatternA[: int(math.floor(self.PatternLength / 2))]
     PatA2 = PatternA[int(math.floor(self.PatternLength / 2)) :]
     PatB1 = PatternB[: int(math.floor(self.PatternLength / 2))]
     PatB2 = PatternB[int(math.floor(self.PatternLength / 2)) :]
     self.Population[-1][0] = copy.deepcopy(PatA1 + PatB2)
     self.Population[-2][0] = copy.deepcopy(PatB1 + PatA2)
Beispiel #11
0
 def test_trimFloatingPointWithPadding2(self):
     """
     Use more complicated times and sampling rate.
     """
     tr = Trace(data=np.arange(111))
     tr.stats.starttime = UTCDateTime(111.11111)
     tr.stats.sampling_rate = 50.0
     org_stats = deepcopy(tr.stats)
     org_data = deepcopy(tr.data)
     # Save memory position of array.
     mem_pos = tr.data.ctypes.data
     # Create temp trace object used for testing.
     temp = deepcopy(tr)
     temp.trim(UTCDateTime(111.22222), UTCDateTime(112.99999), nearest_sample=False)
     # Should again be identical.#XXX not
     temp2 = deepcopy(tr)
     temp2.trim(UTCDateTime(111.21111), UTCDateTime(113.01111), nearest_sample=False)
     np.testing.assert_array_equal(temp.data, temp2.data[1:-1])
     # Check stuff.
     self.assertEqual(temp.stats.starttime, UTCDateTime(111.23111))
     self.assertEqual(temp.stats.endtime, UTCDateTime(112.991110))
     # Check if the data is the same.
     temp = deepcopy(tr)
     temp.trim(UTCDateTime(0), UTCDateTime(1000 * 1000), pad=True)
     self.assertNotEqual(temp.data.ctypes.data, tr.data.ctypes.data)
     # starttime must be in conformance with sampling rate
     t = UTCDateTime(1969, 12, 31, 23, 59, 59, 991110)
     self.assertEqual(temp.stats.starttime, t)
     delta = int((tr.stats.starttime - t) * tr.stats.sampling_rate + 0.5)
     np.testing.assert_array_equal(tr.data, temp.data[delta : delta + 111])
     # Make sure the original Trace object did not change.
     np.testing.assert_array_equal(tr.data, org_data)
     self.assertEqual(tr.data.ctypes.data, mem_pos)
     self.assertEqual(tr.stats, org_stats)
Beispiel #12
0
    def __deepcopy__(self, memo):
        copy = Setting(
            machine_manager=self._machine_manager,
            key=self._key,
            catalog=self._i18n_catalog,
            label=self._label,
            type=self._type,
        )

        copy._description = self._description
        copy._default_value = self._default_value
        copy._visible = self._visible
        copy._category = self._category
        copy._unit = self._unit
        copy._validator = deepcopy(self._validator, memo)
        copy._parent = self._parent
        copy._hide_if_all_children_visible = self._hide_if_all_children_visible
        copy._children = deepcopy(self._children, memo)
        copy._options = deepcopy(self._options, memo)
        copy._inherit = self._inherit
        copy._inherit_function = deepcopy(self._inherit_function, memo)

        copy._warning_description = self._warning_description
        copy._error_description = self._error_description
        copy._enabled_function = deepcopy(self._enabled_function, memo)

        copy._fixChildren()

        return copy
Beispiel #13
0
def fechou(regua, printa_ultima=True, sequencia=None):
    count = 0
    for c in regua:
        if c.has_key("B"):
            count += 1
        if c.has_key("A"):
            break
    global achou
    if count == N:
        if sequencia is not None:  # se for sequencia eh busca estrela ai printa diferente
            print transformaEmString(regua)
            if sequencia is not None:
                print sequencia.sequencia
                aux = copy.deepcopy(sequencia.pai)
                print aux.sequencia
                i = 0
                while aux.pai is not None:
                    aux = copy.deepcopy(aux.pai)
                    print aux.sequencia
                    i += 1
        else:
            if printa_ultima:
                print str(regua)
        achou = True
        return True
    else:
        return False
Beispiel #14
0
    def changed_metadata(self):
        """
        Detects changes to the feed metadata.

        If *any* of the attributes have changed, we use them all.
        """
        changed = False

        past_feed = self.past_feed["feed"]
        new_feed = self.new_feed["feed"]

        if past_feed["title"] != new_feed["title"]:
            changed = True

        if past_feed.get("author", None) != new_feed.get("author", None):
            changed = True

        if len(new_feed.keys()) > len(past_feed.keys()):
            changed = True

        if changed:
            metadata = deepcopy(self.new_feed)
        else:
            metadata = deepcopy(self.past_feed)

        del metadata["entries"]
        return metadata
Beispiel #15
0
    def update_feeds(self):
        """Updates instances of all configured feeds from config"""
        from flexget.feed import Feed

        if not isinstance(self.config["feeds"], dict):
            log.critical("Feeds is in wrong datatype, please read configuration guides")
            return

        # construct feed list
        for name in self.config.get("feeds", {}):
            if not isinstance(self.config["feeds"][name], dict):
                continue
            if name in self.feeds:
                # This feed already has an instance, update it
                self.feeds[name].config = deepcopy(self.config["feeds"][name])
                if not name.startswith("_"):
                    self.feeds[name].enabled = True
            else:
                # Create feed
                feed = Feed(self, name, deepcopy(self.config["feeds"][name]))
                # If feed name is prefixed with _ it's disabled
                if name.startswith("_"):
                    feed.enabled = False
                self.feeds[name] = feed
        # Delete any feed instances that are no longer in the config
        for name in [n for n in self.feeds if n not in self.config["feeds"]]:
            del self.feeds[name]
Beispiel #16
0
def fetch_things(t_class, since, until, batch_fn=None, *query_params, **extra_query_dict):
    """
        Simple utility function to fetch all Things of class t_class
        (spam or not, but not deleted) that were created from 'since'
        to 'until'
    """

    from r2.lib.db.operators import asc

    if not batch_fn:
        batch_fn = lambda x: x

    query_params = [t_class.c._date >= since, t_class.c._date < until, t_class.c._spam == (True, False)] + list(
        query_params
    )
    query_dict = {"sort": asc("_date"), "limit": 100, "data": True}
    query_dict.update(extra_query_dict)

    q = t_class._query(*query_params, **query_dict)

    orig_rules = deepcopy(q._rules)

    things = list(q)
    while things:
        things = batch_fn(things)
        for t in things:
            yield t
        q._rules = deepcopy(orig_rules)
        q._after(t)
        things = list(q)
Beispiel #17
0
 def startVersion(self, REQUEST=None):
     """ """
     if not self.checkPermissionEditObject():
         raise EXCEPTION_NOTAUTHORIZED, EXCEPTION_NOTAUTHORIZED_MSG
     if self.hasVersion():
         raise EXCEPTION_STARTEDVERSION, EXCEPTION_STARTEDVERSION_MSG
     self.checkout = 1
     self.checkout_user = self.REQUEST.AUTHENTICATED_USER.getUserName()
     self.version = reportquestionnaire_item(
         self.title,
         self.description,
         self.coverage,
         self.keywords,
         self.sortorder,
         self.releasedate,
         self.qauthor,
         self.answers,
         self.gl_get_selected_language(),
     )
     self.version._local_properties_metadata = deepcopy(self._local_properties_metadata)
     self.version._local_properties = deepcopy(self._local_properties)
     self.version.setProperties(deepcopy(self.getProperties()))
     self._p_changed = 1
     self.recatalogNyObject(self)
     if REQUEST:
         REQUEST.RESPONSE.redirect("%s/edit_html" % self.absolute_url())
Beispiel #18
0
def fetch_things2(query, chunk_size=100, batch_fn=None, chunks=False):
    """Incrementally run query with a limit of chunk_size until there are
    no results left. batch_fn transforms the results for each chunk
    before returning."""

    assert query._sort, "you must specify the sort order in your query!"

    orig_rules = deepcopy(query._rules)
    query._limit = chunk_size
    items = list(query)
    done = False
    while items and not done:
        # don't need to query again at the bottom if we didn't get enough
        if len(items) < chunk_size:
            done = True

        after = items[-1]

        if batch_fn:
            items = batch_fn(items)

        if chunks:
            yield items
        else:
            for i in items:
                yield i

        if not done:
            query._rules = deepcopy(orig_rules)
            query._after(after)
            items = list(query)
    def copy(self, new_owner, new_game=None):
        new_minion = Minion(
            self.base_attack,
            self.base_health,
            effects=copy.deepcopy(self.effects),
            auras=copy.deepcopy(self.auras),
            buffs=copy.deepcopy(self.buffs),
            deathrattle=copy.deepcopy(self.deathrattle),
            enrage=copy.deepcopy(self.enrage),
        )
        new_minion.health = self.base_health - (self.calculate_max_health() - self.health)
        new_minion.enraged = self.enraged
        new_minion.immune = self.immune
        new_minion.index = self.index
        new_minion.attacks_performed = self.attacks_performed
        new_minion.exhausted = self.exhausted
        new_minion.born = self.born
        card_type = type(self.card)
        new_minion.card = card_type()
        new_minion.player = new_owner
        if new_game:
            new_minion.game = new_game
        else:
            new_minion.game = new_owner.game

        return new_minion
Beispiel #20
0
    def __init__(self, key):
        if not self.check_key(key):
            raise ValueError("invalid key")
        self.key = key
        bytes = [ord(b) for b in str(key)]
        i = j = 0
        l, r = (0, 0)
        # ebgin process of setting up S & P boxes for the key
        from copy import deepcopy

        self.p = deepcopy(self.Pboxes)
        self.s = deepcopy(self.Sboxes)
        klen = len(key)
        for i in xrange(18):
            t = (
                (bytes[j] << 24)
                + (bytes[(j + 1) % klen] << 16)
                + (bytes[(j + 2) % klen] << 8)
                + (bytes[(j + 3) % klen])
            )
            self.p[i] ^= t
            j = (j + 4) % klen
        for i in xrange(0, 18, 2):
            (l, r) = self.crypt_block(l, r, 0)
            self.p[i] = l
            self.p[i + 1] = r
        for i in xrange(4):
            for j in xrange(0, 256, 2):
                (l, r) = self.crypt_block(l, r, 0)
                self.s[i][j] = l
                self.s[i][j + 1] = r
Beispiel #21
0
    def castling(self):
        import copy

        pairs = self.extract_pairs()
        if not pairs:
            return False

        points = []
        for i, pair in enumerate(pairs[::-1]):
            point = copy.deepcopy(pair["l"])
            point["name"] = "%sl" % pairs[i]["name"]
            point["number"] = pairs[i]["l"]["number"]
            point["preset"]["pointname"] = point["name"]
            if not i:
                point["preset"]["startp"] = True
                point["preset"]["tripledash"] = None
            elif point["preset"].get("startp"):
                del point["preset"]["startp"]
                point["preset"]["tripledash"] = 1
            points.append(point)

        for i, pair in enumerate(pairs):
            point = copy.deepcopy(pair["r"])
            point["name"] = "%sr" % pairs[len(pairs) - i - 1]["name"]
            point["number"] = pairs[len(pairs) - i - 1]["r"]["number"]
            point["preset"]["pointname"] = point["name"]
            points.append(point)

        self.points = points
Beispiel #22
0
    def test_copy_continulet_not_started_multiple(self):
        from _continuation import continulet, error
        import copy

        lst = []
        co = continulet(lst.append)
        co2, lst2 = copy.deepcopy((co, lst))
        co3, lst3 = copy.deepcopy((co, lst))
        co4, lst4 = copy.deepcopy((co, lst))
        #
        assert lst == []
        co.switch()
        assert lst == [co]
        #
        assert lst2 == []
        co2.switch()
        assert lst2 == [co2]
        #
        assert lst3 == []
        co3.switch()
        assert lst3 == [co3]
        #
        assert lst4 == []
        co4.switch()
        assert lst4 == [co4]
 def updateFactor(self, factor_type, i):
     """
     IMPLEMENT FOR PART 2
     Update the values remaining for a factor.
     `factor_type` is one of BOX, ROW, COL
     `i` is an index between 0 and 8.
     """
     if factor_type == ROW:
         row = self.row(i)
         conflicts = crossOff(range(1, 10), deepcopy(row))
         values = [x if x not in row else None for x in range(1, 10)]
         self.factorRemaining[factor_type, i] = values
         self.factorNumConflicts[factor_type, i] = conflicts
     if factor_type == COL:
         col = self.col(i)
         conflicts = crossOff(range(1, 10), deepcopy(col))
         values = [x if x not in col else None for x in range(1, 10)]
         self.factorRemaining[factor_type, i] = values
         self.factorNumConflicts[factor_type, i] = conflicts
     if factor_type == BOX:
         box = self.box(i)
         conflicts = crossOff(range(1, 10), deepcopy(box))
         values = [x if x not in box else None for x in range(1, 10)]
         self.factorRemaining[factor_type, i] = values
         self.factorNumConflicts[factor_type, i] = conflicts
def build_it(name, people, sofar, dont_match, size):
    if not people and size == len(sofar):
        # if the people dictionary is empty
        # and the size of the original print it
        printer(name, sofar)
        global count
        count += 1
        if count > 10:
            sys.exit(0)
        return

    for person in people:
        if person == name:
            # don't want to match the person with themself
            continue
        if (name, person) in dont_match or (person, name) in dont_match:
            # don't want to create a pair that is in the don't match list
            continue
        if (person, name) in sofar:
            # don't want a circular match ie Jim buys for Janice and Janice buys for Jim
            continue

        deep_copy_people = copy.deepcopy(people)
        deep_copy_people.remove(person)
        # print "List should be different ", people, deep_copy_people
        deep_copy_sofar = copy.deepcopy(sofar)
        deep_copy_sofar[name] = person
        # print "List should be different sofar ", sofar, deep_copy_sofar
        build_it(person, deep_copy_people, deep_copy_sofar, dont_match, size)
Beispiel #25
0
 def test_readAndWriteViaObsPy(self):
     """
     Read and Write files via L{obspy.Trace}
     """
     gse2file = os.path.join(self.path, "data", "loc_RNON20040609200559.z")
     # read trace
     st1 = read(gse2file)
     st1.verify()
     tr1 = st1[0]
     # write comparison trace
     with NamedTemporaryFile() as tf:
         tempfile = tf.name
         st2 = Stream()
         st2.traces.append(Trace())
         tr2 = st2[0]
         tr2.data = copy.deepcopy(tr1.data)
         tr2.stats = copy.deepcopy(tr1.stats)
         st2.write(tempfile, format="GSE2")
         # read comparison trace
         st3 = read(tempfile)
     st3.verify()
     tr3 = st3[0]
     # check if equal
     self.assertEqual(tr3.stats["station"], tr1.stats["station"])
     self.assertEqual(tr3.stats.npts, tr1.stats.npts)
     self.assertEqual(tr3.stats["sampling_rate"], tr1.stats["sampling_rate"])
     self.assertEqual(tr3.stats.get("channel"), tr1.stats.get("channel"))
     self.assertEqual(tr3.stats.get("starttime"), tr1.stats.get("starttime"))
     self.assertEqual(tr3.stats.get("calib"), tr1.stats.get("calib"))
     self.assertEqual(tr3.stats.gse2.get("vang"), tr1.stats.gse2.get("vang"))
     self.assertEqual(tr3.stats.gse2.get("calper"), tr1.stats.gse2.get("calper"))
     np.testing.assert_equal(tr3.data, tr1.data)
Beispiel #26
0
    def done(self):
        try:
            existing = None
            if self.filename:
                if os.path.exists(self.filename):
                    f = file(self.filename, "rb")
                    try:
                        existing = pickle.load(f)
                    finally:
                        f.close()
                self.stream = file(self.filename, "wb")

            if self.stream:
                current = timedump.current.aggregate(bypass_indices=False)
                if self.drop_storage:
                    timedump.current.clear()
                    timedump.current.storage.drop()
                if existing and isinstance(existing, dict):
                    current = copy.deepcopy(current)
                    existing = copy.deepcopy(existing)
                    self.__update_run(current, existing)

                pickle.dump(current, self.stream)
                if self.filename:
                    self.stream.close()
                    self.stream = None
        except:
            self._log("Couldn't pickle timedump", traceback=True)
Beispiel #27
0
 def testSecondLevelAddModDelDiff(self):
     a = {"some": ["dict"], "with": "some", "key": {"s": "that", "are": ["nes", "ted"]}}
     b = copy.deepcopy(a)
     b["key"]["a"] = "cool stuff"
     b["key"]["s"] = "this"
     del b["key"]["are"]
     ddo_a = DictDiff.create(a, b)
     self.assertEqual(ddo_a.additions_expr(par="obj"), [])
     self.assertEqual([], ddo_a.deletions_expr(par="obj"))
     self.assertEqual(
         ["obj['key']['a'] = 'cool stuff'", "del obj['key']['are']", "obj['key']['s'] = 'this'"],
         ddo_a.modification_expr(par="obj"),
     )
     ddo_d = DictDiff.create(b, a)
     self.assertEqual(ddo_d.deletions_expr(par="obj"), [])
     self.assertEqual([], ddo_d.additions_expr(par="obj"))
     self.assertEqual(
         ["obj['key']['are'] = ['nes', 'ted']", "del obj['key']['a']", "obj['key']['s'] = 'that'"],
         ddo_d.modification_expr(par="obj"),
     )
     c_a = copy.deepcopy(a)
     self.assertEqual(a, c_a)
     c_b = copy.deepcopy(b)
     self.assertEqual(b, c_b)
     ddo_a.patch(c_a)
     self.assertEqual(b, c_a)
     ddo_d.patch(c_b)
     self.assertEqual(a, c_b)
Beispiel #28
0
def cfn_deep_merge(a, b):
    """
    Deep merge two CFN templates, treating CFN magics (see `is_cfn_magic` for more information) as non-mergeable
    Prefers b over a

    :rtype: dict
    :param a: first dictionary
    :param b: second dictionary (overrides a)
    :return: a new dictionary which is a merge of a and b
    """

    # if a and b are dictionaries and both of them aren't cfn magic, merge them
    if isinstance(a, dict) and isinstance(b, dict) and not (is_cfn_magic(a) or is_cfn_magic(b)):
        # we're modifying and returning a, so start off with a copy
        a = copy.deepcopy(a)

        # merge two dictionaries
        for k in b:
            if k in a:
                a[k] = cfn_deep_merge(a[k], b[k])
            else:
                a[k] = copy.deepcopy(b[k])

        return a
    else:
        return copy.deepcopy(b)
Beispiel #29
0
    def clone(self):
        """ Returns a new object identical to the current object """

        obj = copy.deepcopy(self)
        obj.params = copy.deepcopy(self.params)
        obj.details = copy.deepcopy(self.details)
        return obj
Beispiel #30
0
    def __parse__(self, schema):
        with open(schema) as schema_file:
            schema = schema_file.readlines()

        config_item = deepcopy(self.ITEM)

        lineno = 0
        for line in schema:
            lineno += 1
            if line.strip() == "":
                if config_item:
                    self._options.append(config_item)
                    config_item = deepcopy(self.ITEM)
                continue

            name, value = line.replace("\n", "").split("=")
            name = name.strip()
            value = value.strip()

            try:
                config_item[name] = value
            except KeyError:
                print("Invaild line: %s" % line, file=stderr)

            if lineno == len(schema):
                if config_item:
                    self._options.append(config_item)
                    config_item = deepcopy(self.ITEM)
                continue