Replicates common SQLAlchemy attributes from the `source` object to the
    `target` object.
483397
def replicate_attributes(source, target, cache=None):
    ''''''
    target_manager = manager_of_class(type(target))
    column_attrs = set()
    relationship_attrs = set()
    relationship_columns = set()
    for attr in manager_of_class(type(source)).attributes:
        if attr.key not in target_manager:
            # It's not common attribute
            continue
        target_attr = target_manager[attr.key]
        if isinstance(attr.property, ColumnProperty):
            assert isinstance(target_attr.property, ColumnProperty)
            column_attrs.add(attr)
        elif isinstance(attr.property, RelationshipProperty):
            assert isinstance(target_attr.property, RelationshipProperty)
            relationship_attrs.add(attr)
            if attr.property.direction is MANYTOONE:
                relationship_columns.update(attr.property.local_columns)
    for attr in column_attrs:
        if _column_property_in_registry(attr.property, _excluded):
            continue
        elif (not _column_property_in_registry(attr.property, _included) and
                 all(column in relationship_columns
                     for column in attr.property.columns)):
            continue
        setattr(target, attr.key, getattr(source, attr.key))
    for attr in relationship_attrs:
        target_attr_model = target_manager[attr.key].property.argument
        if not is_relation_replicatable(attr):
            continue
        replicate_relation(source, target, attr, target_manager[attr.key],
                           cache=cache)
247390
def source_set(method_name):
    

    def source_set(value, context, **_params):
        method = getattr(context["model"].source, method_name)
        return _set(method, context["key"], value, (), {})

    return source_set
990571
def copy(self):
        
        inst = super(type(self), type(self)).empty(**self.dimensions)
        
        # Need to copy all attributes, fields, relations
        inst.__attributes__ = {k: v.copy() for k, v in self.__attributes__.items()}
        inst.__fields__ = {k: v.copy() for k, v in self.__fields__.items()}
        inst.__relations__ = {k: v.copy() for k, v in self.__relations__.items()}
        inst.maps = {k: m.copy() for k, m in self.maps.items()}
        inst.dimensions = self.dimensions.copy()
        
        return inst
392737
def with_metaclass(Type, skip_attrs=set(('__dict__', '__weakref__'))):
    

    def _clone_with_metaclass(Class):
        attrs = dict((key, value) for key, value in items(vars(Class))
                     if key not in skip_attrs)
        return Type(Class.__name__, Class.__bases__, attrs)

    return _clone_with_metaclass
105264
def copy_database_structure(self, source, destination, tables=None):
        """"""
        # Change database to source
        self.change_db(source)

        if tables is None:
            tables = self.tables

        # Change database to destination
        self.change_db(destination)
        for t in tqdm(tables, total=len(tables), desc='Copying {0} table structure'.format(source)):
            self.copy_table_structure(source, destination, t)
560552
def source_setattr():
    

    def source_setattr(value, context, **_params):
        setattr(context["model"].source, context["key"], value)
        return _attr()

    return source_setattr
1056190
def update_value_from_mapping(source_resource_attr_id, target_resource_attr_id, source_scenario_id, target_scenario_id, **kwargs):
    
    user_id = int(kwargs.get('user_id'))

    rm = aliased(ResourceAttrMap, name='rm')
    #Check the mapping exists.
    mapping = db.DBSession.query(rm).filter(
        or_(
            and_(
                rm.resource_attr_id_a == source_resource_attr_id,
                rm.resource_attr_id_b == target_resource_attr_id
            ),
            and_(
                rm.resource_attr_id_a == target_resource_attr_id,
                rm.resource_attr_id_b == source_resource_attr_id
            )
        )
    ).first()

    if mapping is None:
        raise ResourceNotFoundError("Mapping between %s and %s not found"%
                                    (source_resource_attr_id,
                                     target_resource_attr_id))

    #check scenarios exist
    s1 = _get_scenario(source_scenario_id, user_id)
    s2 = _get_scenario(target_scenario_id, user_id)

    rs = aliased(ResourceScenario, name='rs')
    rs1 = db.DBSession.query(rs).filter(rs.resource_attr_id == source_resource_attr_id,
                                    rs.scenario_id == source_scenario_id).first()
    rs2 = db.DBSession.query(rs).filter(rs.resource_attr_id == target_resource_attr_id,
                                    rs.scenario_id == target_scenario_id).first()

    #3 possibilities worth considering:
    #1: Both RS exist, so update the target RS
    #2: Target RS does not exist, so create it with the dastaset from RS1
    #3: Source RS does not exist, so it must be removed from the target scenario if it exists
    return_value = None#Either return null or return a new or updated resource scenario
    if rs1 is not None:
        if rs2 is not None:
            log.info("Destination Resource Scenario exists. Updating dastaset ID")
            rs2.dataset_id = rs1.dataset_id
        else:
            log.info("Destination has no data, so making a new Resource Scenario")
            rs2 = ResourceScenario(resource_attr_id=target_resource_attr_id, scenario_id=target_scenario_id, dataset_id=rs1.dataset_id)
            db.DBSession.add(rs2)
        db.DBSession.flush()
        return_value = rs2
    else:
        log.info("Source Resource Scenario does not exist. Deleting destination Resource Scenario")
        if rs2 is not None:
            db.DBSession.delete(rs2)

    db.DBSession.flush()
    return return_value
165813
def generate_sql_changes(self):
        
        from_keys = set(self.from_sql_graph.nodes.keys())
        to_keys = set(self.to_sql_graph.nodes.keys())
        new_keys = to_keys - from_keys
        delete_keys = from_keys - to_keys
        changed_keys = set()
        dep_changed_keys = []

        for key in from_keys & to_keys:
            old_node = self.from_sql_graph.nodes[key]
            new_node = self.to_sql_graph.nodes[key]

            # identify SQL changes -- these will alter database.
            if not is_sql_equal(old_node.sql, new_node.sql):
                changed_keys.add(key)

            # identify dependencies change
            old_deps = self.from_sql_graph.dependencies[key]
            new_deps = self.to_sql_graph.dependencies[key]
            removed_deps = old_deps - new_deps
            added_deps = new_deps - old_deps
            if removed_deps or added_deps:
                dep_changed_keys.append((key, removed_deps, added_deps))

        # we do basic sort here and inject dependency keys here.
        # operations built using these keys will properly set operation dependencies which will
        # enforce django to build/keep a correct order of operations (stable_topological_sort).
        keys = self.assemble_changes(new_keys, changed_keys, self.to_sql_graph)
        delete_keys = self.assemble_changes(delete_keys, set(), self.from_sql_graph)

        self._sql_operations = {}
        self._generate_reversed_sql(keys, changed_keys)
        self._generate_sql(keys, changed_keys)
        self._generate_delete_sql(delete_keys)
        self._generate_altered_sql_dependencies(dep_changed_keys)
939511
function (source, target) {
        var tmp;
        target = target || {};
        for (var i in source) {
            if (source.hasOwnProperty(i)) {
                tmp = source[i];
                if (typeof tmp == 'object') {
                    target[i] = utils.isArray(tmp) ? [] : {};
                    utils.clone(source[i], target[i])
                } else {
                    target[i] = tmp;
                }
            }
        }
        return target;
    }
52839
def _copy_params(self):
        
        cls = type(self)
        src_name_attrs = [(x, getattr(cls, x)) for x in dir(cls)]
        src_params = list(filter(lambda nameAttr: isinstance(nameAttr[1], Param), src_name_attrs))
        for name, param in src_params:
            setattr(self, name, param._copy_new_parent(self))
1326930
def copy(self, **kwargs):
        
        for k in kwargs:
            assert k in self._keys, 'Invalid key: %s' % k

        d = self.values()
        d.update(kwargs)
        return self.__class__(**d)
369949
def syncdb(pool=None):
    
    from flask_philo_sqlalchemy.schema import Base  # noqa
    from flask_philo_sqlalchemy.orm import BaseModel  # noqa
    from flask_philo_sqlalchemy.connection import create_pool

    if pool is None:
        pool = create_pool()

    for conn_name, conn in pool.connections.items():
        Base.metadata.create_all(conn.engine)
536598
def clone (self, new_id, new_toolset_properties):
        
        assert isinstance(new_id, basestring)
        assert is_iterable_typed(new_toolset_properties, basestring)
        return self.__class__ (new_id,
                               self.composing_,
                               self.source_types_,
                               self.target_types_and_names_,
                               # Note: this does not remove any subfeatures of <toolset>
                               # which might cause problems
                               property.change (self.requirements_, '<toolset>') + new_toolset_properties)
268801
function copy(source, target) {
  for (var name in source) {
    if (source.hasOwnProperty(name)) {
      target[name] = source[name];
    }
  }
}
1141825
def copy(self, contents=True):
        ''''''
        cp = connection(self._baseiri, self._attr_cls, self._logger)
        if contents: cp.add_many(self._relationships)

        return cp
1176376
def make_copy(self, copy_to):
        

        for attr, value in self.__dict__.items():
            if attr.startswith('__') and attr.endswith('__'):
                continue
            setattr(copy_to, attr, value)
840937
def import_from_dict(cls, session, dict_rep, parent=None,
                         recursive=True, sync=[]):
        """"""
        parent_refs = cls._parent_foreign_key_mappings()
        export_fields = set(cls.export_fields) | set(parent_refs.keys())
        new_children = {c: dict_rep.get(c) for c in cls.export_children
                        if c in dict_rep}
        unique_constrains = cls._unique_constrains()

        filters = []  # Using these filters to check if obj already exists

        # Remove fields that should not get imported
        for k in list(dict_rep):
            if k not in export_fields:
                del dict_rep[k]

        if not parent:
            if cls.export_parent:
                for p in parent_refs.keys():
                    if p not in dict_rep:
                        raise RuntimeError(
                            '{0}: Missing field {1}'.format(cls.__name__, p))
        else:
            # Set foreign keys to parent obj
            for k, v in parent_refs.items():
                dict_rep[k] = getattr(parent, v)

        # Add filter for parent obj
        filters.extend([getattr(cls, k) == dict_rep.get(k)
                        for k in parent_refs.keys()])

        # Add filter for unique constraints
        ucs = [and_(*[getattr(cls, k) == dict_rep.get(k)
               for k in cs if dict_rep.get(k) is not None])
               for cs in unique_constrains]
        filters.append(or_(*ucs))

        # Check if object already exists in DB, break if more than one is found
        try:
            obj_query = session.query(cls).filter(and_(*filters))
            obj = obj_query.one_or_none()
        except MultipleResultsFound as e:
            logging.error('Error importing %s \n %s \n %s', cls.__name__,
                          str(obj_query),
                          yaml.safe_dump(dict_rep))
            raise e

        if not obj:
            is_new_obj = True
            # Create new DB object
            obj = cls(**dict_rep)
            logging.info('Importing new %s %s', obj.__tablename__, str(obj))
            if cls.export_parent and parent:
                setattr(obj, cls.export_parent, parent)
            session.add(obj)
        else:
            is_new_obj = False
            logging.info('Updating %s %s', obj.__tablename__, str(obj))
            # Update columns
            for k, v in dict_rep.items():
                setattr(obj, k, v)

        # Recursively create children
        if recursive:
            for c in cls.export_children:
                child_class = cls.__mapper__.relationships[c].argument.class_
                added = []
                for c_obj in new_children.get(c, []):
                    added.append(child_class.import_from_dict(session=session,
                                                              dict_rep=c_obj,
                                                              parent=obj,
                                                              sync=sync))
                # If children should get synced, delete the ones that did not
                # get updated.
                if c in sync and not is_new_obj:
                    back_refs = child_class._parent_foreign_key_mappings()
                    delete_filters = [getattr(child_class, k) ==
                                      getattr(obj, back_refs.get(k))
                                      for k in back_refs.keys()]
                    to_delete = set(session.query(child_class).filter(
                        and_(*delete_filters))).difference(set(added))
                    for o in to_delete:
                        logging.info('Deleting %s %s', c, str(obj))
                        session.delete(o)

        return obj