Return module for relation based on its role and interface, or None.

    Prefers new location (reactive/relations) over old (hooks/relations).
978871
def _relation_module(role, interface):
    
    _append_path(hookenv.charm_dir())
    _append_path(os.path.join(hookenv.charm_dir(), 'hooks'))
    base_module = 'relations.{}.{}'.format(interface, role)
    for module in ('reactive.{}'.format(base_module), base_module):
        if module in sys.modules:
            break
        try:
            importlib.import_module(module)
            break
        except ImportError:
            continue
    else:
        hookenv.log('Unable to find implementation for relation: '
                    '{} of {}'.format(role, interface), hookenv.ERROR)
        return None
    return sys.modules[module]
228283
function (roles) {
              roles.map(function (role) {
                return Role.findOrCreate({
                  where: {
                    code: role,
                    ownerId: req[options.auth.model].id
                  },

                  defaults: {
                    code: role,
                    ownerId: req[options.auth.model].id
                  }
                }).spread(function (role, created) {
                  return role
                }).catch(function (err) {
                  res.database(err)
                });
              });

              return Promise.all(roles);
            }
810697
function getDependency(dependency) {
            if (dependency) {
                return angular.isString(dependency) ? $injector.get(dependency) : dependency;
            }

            return undefined;
        }
1189666
def get_relation(self, relation):
        
        from .relations import Relation

        with Relation.no_constraints(True):
            rel = getattr(self.get_model(), relation)()

        nested = self._nested_relations(relation)

        if len(nested) > 0:
            rel.get_query().with_(nested)

        return rel
220142
def match_relations(self, el, relation):
        """"""

        found = False

        if relation[0].rel_type.startswith(':'):
            found = self.match_future_relations(el, relation)
        else:
            found = self.match_past_relations(el, relation)

        return found
235774
RelationImpl buildRelation(EdgeElement edge, RelationType type, Role owner, Role value) {
        return getOrBuildConcept(edge, (e) -> RelationImpl.create(RelationEdge.create(type, owner, value, edge)));
    }
274716
def where(self, relation, filter_fn):
        '''  '''
        assert type(relation).__name__ in {'str','unicode'}, 'where needs the first arg to be a string'
        assert callable(filter_fn), 'filter_fn needs to be callable'
        return VList(i for i in self if relation in i._relations() and any(filter_fn(_()) for _ in i[relation]))
427281
def get_relationships(module_name, id, related_to, opts={})
    login! unless logged_in?
    options = { 
      :query => '',
      :fields => [], 
      :link_fields => [],
      :related_fields => [], 
      :deleted => 0
    }.merge! opts  

    json = <<-EOF
      {
        "session": "#{@sugar_session_id}",
        "module_name": "#{module_name}",
        "module_id": "#{id}",
        "link_field_name": "#{related_to.downcase}",
        "related_module_query": "#{options[:query]}",
        "related_fields": #{((options and options[:related_fields].present?) ? options[:related_fields] : resolve_related_fields(module_name, related_to) ).to_json},     
        "related_module_link_name_to_fields_array": #{options[:link_fields].to_json},
        "deleted": #{options[:deleted]}
      }
    EOF
    #puts "#{json}"
    json.gsub!(/^\s{6}/,'')
    SugarCRM::Response.new(send!(:get_relationships, json), @session, {:always_return_array => true}).to_obj
  end
721826
def get_relations(self, rel_id=None, **kwargs):
        
        return self.get_elements(Relation, elem_id=rel_id, **kwargs)
564695
def find_related_module(app, related_name):
    """"""

    try:
        app_path = importlib.import_module(app).__path__
    except ImportError as exc:
        warn('Autodiscover: Error importing %s.%s: %r' % (
            app, related_name, exc,
        ))
        return
    except AttributeError:
        return

    try:
        f, _, _ = imp.find_module(related_name, app_path)
        # f is returned None when app_path is a module
        f and f.close()
    except ImportError:
        return

    return importlib.import_module('{0}.{1}'.format(app, related_name))
1188056
private NodeInterface getRelatedNode(boolean add) {

		T relatedNode = null;

		if ((currentObject != null) && (currentObject instanceof NodeInterface)) {

			NodeInterface localNode = (NodeInterface) currentObject;
			relatedNode = localNode.getProperty(sourceKey);
			
			if (relatedNode == null && add && sourceKey instanceof RelationProperty) {

				final RelationProperty relationProperty = (RelationProperty)sourceKey;
				final App app                           = StructrApp.getInstance();
				final Class<T> relatedType              = relationProperty.getTargetType();

				if (relatedType != null) {
					
					try {
						relatedNode = app.create(relatedType);
						relationProperty.addSingleElement(securityContext, localNode, relatedNode);

					} catch (FrameworkException fex) {

						logger.warn("", fex);
					}
					
				} else {
					
					logger.error("Related type was null for {}", currentObject);
				}
			}
		}

		return relatedNode;
	}
577276
def get_module(self, modulename, revision=None):
        """"""
        if revision is None and modulename in self.revs:
            (revision, _handle) = self._get_latest_rev(self.revs[modulename])
        if revision is not None:
            if (modulename,revision) in self.modules:
                return self.modules[(modulename, revision)]
        else:
            return None
1169706
function(resolve) {
    var self = this.chain()

    // if .find(null) was called
    if (self.getInternal('exec_null')) {
      return Promise.resolve(null)
    }

    var relation = self.getInternal('relation')

    if (relation && typeof relation.loadWithCollection === 'function') {
      const promise = relation.loadWithCollection(self)
      if (promise && promise.then) return promise.then(resolve)
    }

    var dataLoaded = self.getInternal('data_loaded')
    var options = self.getExecOptions()
    var data = {}

    if (dataLoaded) data.result = dataLoaded

    return self
      .callInterceptors('beforeFind', [options])
      .then(function() {
        return self.callInterceptors('onFind', [options, data], {
          executeInParallel: true
        })
      })
      .then(function() {
        return self.callInterceptors('afterFind', [data])
      })
      .then(function() {
        if (typeof resolve === 'function') return resolve(data.result)
        return data.result
      })
  }
1191938
def _get_has_relation_query(self, relation):
        
        from .relations import Relation

        return Relation.no_constraints(
            lambda: getattr(self.get_model(), relation)()
        )
541770
function connectStore(modules) {
  var mapStateToProps = function mapStateToProps(state, props) {
    var finalState = {};
    Object.keys(modules).forEach(function (key) {
      var moduleInstance = modules[key];
      var module_name = moduleInstance.module && moduleInstance.module.name || moduleInstance.name;
      var stateObj = state[module_name];
      if (moduleInstance.get) {
        var filter_array = moduleInstance.get.split(",");
        stateObj = (0, _helpers.pluck)(stateObj, filter_array);
      }
      stateObj = attachModuleSelectors(moduleInstance, stateObj, state, props);
      finalState[key] = stateObj;
    });
    return finalState;
  };

  var mapDispatchToProps = function mapDispatchToProps(dispatch) {
    var finalProps = {};
    Object.keys(modules).forEach(function (key) {
      var moduleInstance = modules[key];
      var actions_obj = {};
      var module_actions = moduleInstance.module && moduleInstance.module.actions || moduleInstance.actions;
      if (module_actions) {
        Object.keys(module_actions).forEach(function (action_key) {
          var action = module_actions[action_key];
          actions_obj[action_key] = function () {
            return dispatch(action.apply(undefined, arguments));
          };
        });
        finalProps[key] = actions_obj;
      }
    });
    return finalProps;
  };
  var mergeProps = function mergeProps(state, actions, ownProps) {
    var finalModule = {};
    Object.keys(state).forEach(function (key) {
      var module_state = state[key];
      var module_actions = actions[key];
      finalModule[key] = Object.assign({}, module_state, module_actions);
    });
    return Object.assign({}, finalModule, ownProps);
  };
  return (0, _reactRedux.connect)(mapStateToProps, mapDispatchToProps, mergeProps, {
    pure: true,
    areStatePropsEqual: function areStatePropsEqual(a, b) {
      return (0, _helpers.areSame)(a, b);
    }
  });
}
1205240
RelationImpl buildRelation(VertexElement vertex, RelationType type) {
        return getOrBuildConcept(vertex, (v) -> RelationImpl.create(buildRelationReified(v, type)));
    }
215405
def hook(opts = {})
      opts[:force] ||= false
      Nest.fetch(base_module).add(self)
      Agency.instance.recruit(self)

      @previously_defined = currently_defined?
      if previously_defined? || !opts[:force]
        @original_value = base_module.const_get(constant_name, false)
      end
      and_return(@new_value)
      self
    end