ask question for a relationship creation
188579
function askForRelationship(done) {
    const context = this.context;
    const name = context.name;
    this.log(chalk.green('\nGenerating relationships to other entities\n'));
    const fieldNamesUnderscored = context.fieldNamesUnderscored;
    const prompts = [
        {
            type: 'confirm',
            name: 'relationshipAdd',
            message: 'Do you want to add a relationship to another entity?',
            default: true
        },
        {
            when: response => response.relationshipAdd === true,
            type: 'input',
            name: 'otherEntityName',
            validate: input => {
                if (!/^([a-zA-Z0-9_]*)$/.test(input)) {
                    return 'Your other entity name cannot contain special characters';
                }
                if (input === '') {
                    return 'Your other entity name cannot be empty';
                }
                if (jhiCore.isReservedKeyword(input, 'JAVA')) {
                    return 'Your other entity name cannot contain a Java reserved keyword';
                }
                if (input.toLowerCase() === 'user' && context.applicationType === 'microservice') {
                    return "Your entity cannot have a relationship with User because it's a gateway entity";
                }
                return true;
            },
            message: 'What is the name of the other entity?'
        },
        {
            when: response => response.relationshipAdd === true,
            type: 'input',
            name: 'relationshipName',
            validate: input => {
                if (!/^([a-zA-Z0-9_]*)$/.test(input)) {
                    return 'Your relationship cannot contain special characters';
                }
                if (input === '') {
                    return 'Your relationship cannot be empty';
                }
                if (input.charAt(0) === input.charAt(0).toUpperCase()) {
                    return 'Your relationship cannot start with an upper case letter';
                }
                if (input === 'id' || fieldNamesUnderscored.includes(_.snakeCase(input))) {
                    return 'Your relationship cannot use an already existing field name';
                }
                if (jhiCore.isReservedKeyword(input, 'JAVA')) {
                    return 'Your relationship cannot contain a Java reserved keyword';
                }
                return true;
            },
            message: 'What is the name of the relationship?',
            default: response => _.lowerFirst(response.otherEntityName)
        },
        {
            when: response => response.relationshipAdd === true,
            type: 'list',
            name: 'relationshipType',
            message: 'What is the type of the relationship?',
            choices: response => {
                const opts = [
                    {
                        value: 'many-to-one',
                        name: 'many-to-one'
                    },
                    {
                        value: 'many-to-many',
                        name: 'many-to-many'
                    },
                    {
                        value: 'one-to-one',
                        name: 'one-to-one'
                    }
                ];
                if (response.otherEntityName.toLowerCase() !== 'user') {
                    opts.unshift({
                        value: 'one-to-many',
                        name: 'one-to-many'
                    });
                }
                return opts;
            },
            default: 0
        },
        {
            when: response =>
                response.relationshipAdd === true &&
                response.otherEntityName.toLowerCase() !== 'user' &&
                (response.relationshipType === 'many-to-many' || response.relationshipType === 'one-to-one'),
            type: 'confirm',
            name: 'ownerSide',
            message: 'Is this entity the owner of the relationship?',
            default: false
        },
        {
            when: response =>
                context.databaseType === 'sql' &&
                response.relationshipAdd === true &&
                response.relationshipType === 'one-to-one' &&
                (response.ownerSide === true || response.otherEntityName.toLowerCase() === 'user'),
            type: 'confirm',
            name: 'useJPADerivedIdentifier',
            message: 'Do you want to use JPA Derived Identifier - @MapsId?',
            default: false
        },
        {
            when: response =>
                response.relationshipAdd === true &&
                (response.relationshipType === 'one-to-many' ||
                    ((response.relationshipType === 'many-to-many' || response.relationshipType === 'one-to-one') &&
                        response.otherEntityName.toLowerCase() !== 'user')),
            type: 'input',
            name: 'otherEntityRelationshipName',
            message: 'What is the name of this relationship in the other entity?',
            default: response => _.lowerFirst(name)
        },
        {
            when: response =>
                response.relationshipAdd === true &&
                (response.relationshipType === 'many-to-one' ||
                    (response.relationshipType === 'many-to-many' && response.ownerSide === true) ||
                    (response.relationshipType === 'one-to-one' && response.ownerSide === true)),
            type: 'input',
            name: 'otherEntityField',
            message: response =>
                `When you display this relationship on client-side, which field from '${
                    response.otherEntityName
                }' do you want to use? This field will be displayed as a String, so it cannot be a Blob`,
            default: 'id'
        },
        {
            when: response =>
                response.relationshipAdd === true &&
                response.otherEntityName.toLowerCase() !== context.name.toLowerCase() &&
                (response.relationshipType === 'many-to-one' ||
                    (response.relationshipType === 'many-to-many' &&
                        (response.ownerSide === true || response.otherEntityName.toLowerCase() === 'user')) ||
                    (response.relationshipType === 'one-to-one' &&
                        (response.ownerSide === true || response.otherEntityName.toLowerCase() === 'user'))),
            type: 'confirm',
            name: 'relationshipValidate',
            message: 'Do you want to add any validation rules to this relationship?',
            default: false
        },
        {
            when: response => response.relationshipValidate === true,
            type: 'checkbox',
            name: 'relationshipValidateRules',
            message: 'Which validation rules do you want to add?',
            choices: [
                {
                    name: 'Required',
                    value: 'required'
                }
            ],
            default: 0
        }
    ];
    this.prompt(prompts).then(props => {
        if (props.relationshipAdd) {
            const relationship = {
                relationshipName: props.relationshipName,
                otherEntityName: _.lowerFirst(props.otherEntityName),
                relationshipType: props.relationshipType,
                relationshipValidateRules: props.relationshipValidateRules,
                otherEntityField: props.otherEntityField,
                ownerSide: props.ownerSide,
                useJPADerivedIdentifier: props.useJPADerivedIdentifier,
                otherEntityRelationshipName: props.otherEntityRelationshipName
            };

            if (props.otherEntityName.toLowerCase() === 'user') {
                relationship.ownerSide = true;
                relationship.otherEntityField = 'login';
                relationship.otherEntityRelationshipName = _.lowerFirst(name);
            }

            fieldNamesUnderscored.push(_.snakeCase(props.relationshipName));
            context.relationships.push(relationship);
        }
        logFieldsAndRelationships.call(this);
        if (props.relationshipAdd) {
            askForRelationship.call(this, done);
        } else {
            this.log('\n');
            done();
        }
    });
}
399176
def create(request):
    """"""

    errors = []
    success = False
    listOfResponses = ['', '', '']  # 3 Blank lines by default
    title = ''
    description = ''
    id = ''

    if request.method == 'POST':  # User saved the form
        # Retrieve parameters
        title = request.form.get('title')
        description = request.form.get('description')

        listOfResponses = []
        for rep in request.form.getlist('rep[]'):
            if rep != '':
                listOfResponses.append(rep)

        # Test if everything is ok
        if title == "":
            errors.append("Please set a title !")

        if len(listOfResponses) == 0:
            errors.append("Please set at least one response !")

        # Can we save the new question ?
        if len(errors) == 0:
            # Yes. Let save data
            curDB.execute("INSERT INTO Poll (title, description) VALUES (?, ?)", (title, description))

            # The id of the poll
            id = curDB.lastrowid

            # Insert responses
            for rep in listOfResponses:
                curDB.execute("INSERT INTO Response (pollId, title) VALUES (?, ?)", (id, rep))

            coxDB.commit()

            success = True

        # Minimum of 3 lines of questions
        while len(listOfResponses) < 3:
            listOfResponses.append('')

    return {'errors': errors, 'success': success, 'listOfResponses': listOfResponses, 'title': title, 'description': description, 'id': id}
245956
function(req, res, next, relationship) {
		if(req.fullModel.hasRelationship(relationship)) {
			return next();
		}

		return responseUtils.respond(res, 400); //Malformed syntax or a bad query
	}
866200
def relationships
      r = Relationships.new
      r + [tables.relationships,
           worksheet_comments.relationships,
           hyperlinks.relationships,
           worksheet_drawing.relationship,
           pivot_tables.relationships].flatten.compact || []
      r
    end
798533
def _ask(question, default=None, data_type='str', show_hint=False):
    """"""

    data = default

    if data_type == 'bool':
        data = None
        default_string = "Y" if default else "N"

        while data not in ('Y', 'J', 'N', '1', '0'):
            data = input("%s? [%s]: " % (question, default_string)).upper()

            if data == '':
                return default

        return data in ('Y', 'J', '1')

    elif data_type in ('str', 'unicode'):
        if show_hint:
            msg = "%s? [%s] (%s): " % (question, default, data_type)
        else:
            msg = question

        data = input(msg)

        if len(data) == 0:
            data = default
    elif data_type == 'int':
        if show_hint:
            msg = "%s? [%s] (%s): " % (question, default, data_type)
        else:
            msg = question

        data = input(msg)

        if len(data) == 0:
            data = int(default)
        else:
            data = int(data)

    return data
1191502
function defineRelationshipResolution(
  schema: GraphQLSchema,
  relationships: Relationship[],
  database: DatabaseInterface,
): void {
  relationships.forEach(relationship => {
    defineFieldResolve(
      schema,
      relationship.path[0].fromType,
      relationship.fieldName,
      database.generateRelationshipResolver(relationship),
    );
  });
}
471869
def post(self, *args, **kwargs):
        """"""
        json_data = request.get_json() or {}

        relationship_field, model_relationship_field, related_type_, related_id_field = self._get_relationship_data()

        if 'data' not in json_data:
            raise BadRequest('You must provide data with a "data" route node', source={'pointer': '/data'})
        if isinstance(json_data['data'], dict):
            if 'type' not in json_data['data']:
                raise BadRequest('Missing type in "data" node', source={'pointer': '/data/type'})
            if 'id' not in json_data['data']:
                raise BadRequest('Missing id in "data" node', source={'pointer': '/data/id'})
            if json_data['data']['type'] != related_type_:
                raise InvalidType('The type field does not match the resource type', source={'pointer': '/data/type'})
        if isinstance(json_data['data'], list):
            for obj in json_data['data']:
                if 'type' not in obj:
                    raise BadRequest('Missing type in "data" node', source={'pointer': '/data/type'})
                if 'id' not in obj:
                    raise BadRequest('Missing id in "data" node', source={'pointer': '/data/id'})
                if obj['type'] != related_type_:
                    raise InvalidType('The type provided does not match the resource type',
                                      source={'pointer': '/data/type'})

        self.before_post(args, kwargs, json_data=json_data)

        obj_, updated = self._data_layer.create_relationship(json_data,
                                                             model_relationship_field,
                                                             related_id_field,
                                                             kwargs)

        status_code = 200
        result = {'meta': {'message': 'Relationship successfully created'}}

        if updated is False:
            result = ''
            status_code = 204

        final_result = self.after_post(result, status_code)

        return final_result
128098
protected void processRelationship(final ParserData parserData, final SpecNodeWithRelationships specNode,
            final Relationship relationship) {
        final String relatedId = relationship.getSecondaryRelationshipId();
        // The relationship points to a target so it must be a level or topic
        if (relatedId.toUpperCase(Locale.ENGLISH).matches(ProcessorConstants.TARGET_REGEX)) {
            if (parserData.getTargetTopics().containsKey(relatedId) && !parserData.getTargetLevels().containsKey(relatedId)) {
                specNode.addRelationshipToTarget(parserData.getTargetTopics().get(relatedId), relationship.getType(),
                        relationship.getRelationshipTitle());
            } else if (!parserData.getTargetTopics().containsKey(relatedId) && parserData.getTargetLevels().containsKey(relatedId)) {
                specNode.addRelationshipToTarget(parserData.getTargetLevels().get(relatedId), relationship.getType(),
                        relationship.getRelationshipTitle());
            } else {
                final SpecTopic dummyTopic = new SpecTopic(-1, "");
                dummyTopic.setTargetId(relatedId);
                dummyTopic.setUniqueId("-1");
                specNode.addRelationshipToTarget(dummyTopic, relationship.getType(), relationship.getRelationshipTitle());
            }
        }
        // The relationship isn't a target so it must point to a topic directly
        else {
            if (!CSConstants.NEW_TOPIC_ID_PATTERN.matcher(relatedId).matches()) {
                // The relationship isn't a unique new topic so it will contain the line number in front of
                // the topic ID
                if (!relatedId.startsWith("X")) {
                    int count = 0;
                    SpecTopic relatedTopic = null;

                    // Get the related topic and count if more then one is found
                    for (final Map.Entry<String, SpecTopic> specTopicEntry : parserData.getSpecTopics().entrySet()) {
                        if (specTopicEntry.getKey().matches("^[\\w\\d]+-" + relatedId + "$")) {
                            relatedTopic = specTopicEntry.getValue();
                            count++;
                        }
                    }

                    /*
                     * Add the relationship to the node even if the relationship isn't duplicated
                     * and the related topic isn't the current topic. This is so it shows up in the
                     * output.
                     */
                    if (count > 0) {
                        specNode.addRelationshipToTopic(relatedTopic, relationship.getType(), relationship.getRelationshipTitle());
                    } else {
                        final SpecTopic dummyTopic = new SpecTopic(-1, "");
                        dummyTopic.setId(relatedId);
                        dummyTopic.setUniqueId("-1");
                        specNode.addRelationshipToTopic(dummyTopic, relationship.getType(), relationship.getRelationshipTitle());
                    }
                } else {
                    final SpecTopic dummyTopic = new SpecTopic(-1, "");
                    dummyTopic.setId(relatedId);
                    dummyTopic.setUniqueId("-1");
                    specNode.addRelationshipToTopic(dummyTopic, relationship.getType(), relationship.getRelationshipTitle());
                }
            } else {
                if (parserData.getSpecTopics().containsKey(relatedId)) {
                    final SpecTopic relatedSpecTopic = parserData.getSpecTopics().get(relatedId);

                    // Check that a duplicate doesn't exist, because if it does the new topic isn't unique
                    String duplicatedId = "X" + relatedId.substring(1);
                    boolean duplicateExists = false;
                    for (String uniqueTopicId : parserData.getSpecTopics().keySet()) {
                        if (uniqueTopicId.matches("^[\\w\\d]+-" + duplicatedId + "$")) {
                            duplicateExists = true;
                            break;
                        }
                    }

                    if (relatedSpecTopic != specNode) {
                        if (!duplicateExists) {
                            specNode.addRelationshipToTopic(relatedSpecTopic, relationship.getType(), relationship.getRelationshipTitle());
                        } else {
                            // Only create a new target if one doesn't already exist
                            if (relatedSpecTopic.getTargetId() == null) {
                                String targetId = ContentSpecUtilities.generateRandomTargetId(relatedSpecTopic.getUniqueId());
                                while (parserData.getTargetTopics().containsKey(targetId) || parserData.getTargetLevels().containsKey(
                                        targetId)) {
                                    targetId = ContentSpecUtilities.generateRandomTargetId(relatedSpecTopic.getUniqueId());
                                }
                                parserData.getSpecTopics().get(relatedId).setTargetId(targetId);
                                parserData.getTargetTopics().put(targetId, relatedSpecTopic);
                            }
                            specNode.addRelationshipToTopic(relatedSpecTopic, relationship.getType(), relationship.getRelationshipTitle());
                        }
                    }
                } else {
                    final SpecTopic dummyTopic = new SpecTopic(-1, "");
                    dummyTopic.setId(relatedId);
                    dummyTopic.setUniqueId("-1");
                    specNode.addRelationshipToTopic(dummyTopic, relationship.getType(), relationship.getRelationshipTitle());
                }
            }
        }
    }
181578
def ask(question, no_input=False):
    """"""
    if no_input:
        return True
    else:
        input_ = input('%s [Y/n] ' % question)
        input_ = input_.strip().lower()
        if input_ in ('y', 'yes', ''):
            return True
        if input_ in ('n', 'no'):
            return False
        print('Invalid selection')
1014162
def addRelationships(
        self,
        data: list,
        LIMIT: int = 20,
        _print: bool = True,
        crawl: bool = False,
        ) -> list:
        
        url_base = self.base_url + '/api/1/term/add-relationship'
        relationships = []
        for relationship in data:
            relationship.update({
                'term1_version': relationship['term1_version'],
                'term2_version': relationship['term2_version'],
                'relationship_term_version': relationship['relationship_term_version']
            })
            relationships.append((url_base, relationship))
        return self.post(
            relationships,
            LIMIT = LIMIT,
            action = 'Adding Relationships',
            _print = _print,
            crawl = crawl,
        )
1053095
def run_question(self, question, input_func=_stdin_):
        """"""
        qi = '[%d/%d] ' % (self.qcount, self.qtotal)
        print('%s %s:' % (qi, question['label']))
        while True:
            # ask for user input until we get a valid one
            ans = input_func('%s > ' % self.format_choices())
            if self.is_answer_valid(ans): 
                question['answer'] = int(ans)
                break
            else:
                if ans is '?': print(question['description'])
                else: print('Invalid answer.')
        self.qcount += 1
358884
def create_physical_relationship(manager, physical_handle_id, other_handle_id, rel_type):
    
    other_meta_type = get_node_meta_type(manager, other_handle_id)
    if other_meta_type == 'Physical':
        if rel_type == 'Has' or rel_type == 'Connected_to':
            return _create_relationship(manager, physical_handle_id, other_handle_id, rel_type)
    elif other_meta_type == 'Location' and rel_type == 'Located_in':
        return _create_relationship(manager, physical_handle_id, other_handle_id, rel_type)
    raise exceptions.NoRelationshipPossible(physical_handle_id, 'Physical', other_handle_id, other_meta_type, rel_type)
1048366
def get_relationships_for_source_on_date(self, source_id, from_, to):
        """"""
        # Implemented from azosid template for -
        # osid.relationship.RelationshipLookupSession.get_relationships_for_source_on_date_template
        if self._can('lookup'):
            return self._provider_session.get_relationships_for_source_on_date(source_id, from_, to)
        self._check_lookup_conditions()  # raises PermissionDenied
        query = self._query_session.get_relationship_query()
        query.match_source_id(source_id, match=True)
        query.match_date(from_, to, match=True)
        return self._try_harder(query)
905352
def add_question(self, qname, rdtype, rdclass=dns.rdataclass.IN):
        

        self._set_section(QUESTION)
        before = self.output.tell()
        qname.to_wire(self.output, self.compress, self.origin)
        self.output.write(struct.pack("!HH", rdtype, rdclass))
        after = self.output.tell()
        if after >= self.max_size:
            self._rollback(before)
            raise dns.exception.TooBig
        self.counts[QUESTION] += 1
76073
def setup(self):
    
    cmds = [
      """
        create table if not exists relations (
          id integer not null primary key,
          name text not null unique,
          completed_at datetime
        );
      """,
      """
        create table if not exists transfers (
          relation_id integer not null references relations (id) on delete cascade,
          old_id text not null,
          new_id text,
          primary key (relation_id, old_id)
        );
      """,
      """
        create index if not exists transfers_relation_id_idx on transfers (relation_id);
      """
    ]

    for cmd in cmds:
      self.data_access.execute(cmd)
    self.data_access.commit()
    return self
734645
def ask(question, answer_type=String, &details)
     $log.debug "XXXX inside ask win #{@window} "
      @window ||= _create_footer_window
      #@window.show #unless @window.visible?
    
      @question ||= Question.new(question, answer_type, &details)
      say(@question) #unless @question.echo == true

      @completion_proc = @question.completion_proc
      @change_proc = @question.change_proc
      @key_handler_proc = @question.key_handler_proc
      @default = @question.default
      $log.debug "XXX: ASK RBGETS got default: #{@default} "
      @help_text = @question.help_text
      @answer_type = @question.answer_type
      if @question.answer_type.is_a? Array
        @completion_proc = Proc.new{|str| @answer_type.dup.grep Regexp.new("^#{str}") }
      end

      begin
        # FIXME a C-c still returns default to user !
        @answer = @question.answer_or_default(get_response) 
        unless @question.valid_answer?(@answer)
          explain_error(:not_valid)
          raise QuestionError
        end

        @answer = @question.convert(@answer)

        if @question.in_range?(@answer)
          if @question.confirm
            # need to add a layer of scope to ask a question inside a
            # question, without destroying instance data
            context_change = self.class.new(@input, @output, @wrap_at, @page_at)
            if @question.confirm == true
              confirm_question = "Are you sure?  "
            else
              # evaluate ERb under initial scope, so it will have
              # access to @question and @answer
              template  = ERB.new(@question.confirm, nil, "%")
              confirm_question = template.result(binding)
            end
            unless context_change.agree(confirm_question)
              explain_error(nil)
              raise QuestionError
            end
          end

          @answer
        else
          explain_error(:not_in_range)
          raise QuestionError
        end
      rescue QuestionError
        retry
      rescue ArgumentError, NameError => error
        #raise
        raise if error.is_a?(NoMethodError)
        if error.message =~ /ambiguous/
          # the assumption here is that OptionParser::Completion#complete
          # (used for ambiguity resolution) throws exceptions containing 
          # the word 'ambiguous' whenever resolution fails
          explain_error(:ambiguous_completion)
        else
          explain_error(:invalid_type)
        end
        retry
      rescue Question::NoAutoCompleteMatch
        explain_error(:no_completion)
        retry
      rescue Interrupt
        $log.warn "User interrupted ask() get_response does not want operation to proceed"
        return nil
      ensure
        @question = nil    # Reset Question object.
        $log.debug "XXX: HIDE B AT ENSURE OF ASK"
        hide_bottomline # assuming this method made it visible, not sure if this is called.
      end
    end
871007
def create(self, user_id, name, department=None, position=None,
               mobile=None, gender=0, tel=None, email=None,
               weixin_id=None, extattr=None):
        
        user_data = optionaldict()
        user_data['userid'] = user_id
        user_data['name'] = name
        user_data['gender'] = gender
        user_data['department'] = department
        user_data['position'] = position
        user_data['mobile'] = mobile
        user_data['tel'] = tel
        user_data['email'] = email
        user_data['weixinid'] = weixin_id
        user_data['extattr'] = extattr

        return self._post(
            'user/create',
            data=user_data
        )