Template object for key generation form
546370
function tpl_key_create_form($attrib)
    {
        $attrib += array('id' => 'rcmKeyCreateForm');
        $table  = new html_table(array('cols' => 2));

        // get user's identities
        $identities = $this->rc->user->list_identities(null, true);
        $checkbox   = new html_checkbox(array('name' => 'identity[]'));

        $plugin     = $this->rc->plugins->exec_hook('enigma_user_identities', array('identities' => $identities));
        $identities = $plugin['identities'];

        foreach ($identities as $idx => $ident) {
            $name = empty($ident['name']) ? ($ident['email']) : $ident['ident'];
            $attr = array('value' => $idx, 'data-name' => $ident['name'], 'data-email' => $ident['email']);
            $identities[$idx] = html::label(null, $checkbox->show($idx, $attr) . rcube::Q($name));
        }

        $table->add('title', html::label('key-name', rcube::Q($this->enigma->gettext('newkeyident'))));
        $table->add(null, implode($identities, "\n"));

        // Key size
        $select = new html_select(array('name' => 'size', 'id' => 'key-size'));
        $select->add($this->enigma->gettext('key2048'), '2048');
        $select->add($this->enigma->gettext('key4096'), '4096');

        $table->add('title', html::label('key-size', rcube::Q($this->enigma->gettext('newkeysize'))));
        $table->add(null, $select->show());

        // Password and confirm password
        $table->add('title', html::label('key-pass', rcube::Q($this->enigma->gettext('newkeypass'))));
        $table->add(null, rcube_output::get_edit_field('password', '',
            array('id' => 'key-pass', 'size' => $attrib['size'], 'required' => true), 'password'));

        $table->add('title', html::label('key-pass-confirm', rcube::Q($this->enigma->gettext('newkeypassconfirm'))));
        $table->add(null, rcube_output::get_edit_field('password-confirm', '',
            array('id' => 'key-pass-confirm', 'size' => $attrib['size'], 'required' => true), 'password'));

        $this->rc->output->add_gui_object('keyform', $attrib['id']);
        $this->rc->output->add_label('enigma.keygenerating', 'enigma.formerror',
            'enigma.passwordsdiffer', 'enigma.keygenerateerror', 'enigma.noidentselected',
            'enigma.keygennosupport');

        return $this->rc->output->form_tag(array(), $table->show($attrib));
    }
14226
private String buildObjectKey(final Object object) {

        String objectKey = null;
        final Class<?> objectClass = object.getClass();

        final KeyGenerator typeGenerator = objectClass.getAnnotation(KeyGenerator.class);
        if (typeGenerator == null) {
            objectKey = generateAggregatedKey(object);
        } else {
            objectKey = generateTypeKey(object, typeGenerator);
        }

        // If no Type keyGenerator neither Method Generator were used, use the default toString method
        if (objectKey == null) {
            objectKey = object.toString();
        }

        return objectKey;
    }
628366
def lookup_field(key, lookup_type=None, placeholder=None, html_class="div",
                 select_type="strapselect", mapping="uuid"):
    """"""

    if lookup_type is None:
        lookup_type = key

    if placeholder is None:
        placeholder = "Select a " + lookup_type

    result = {
        'key': key,
        'htmlClass': html_class,
        'type': select_type,
        'placeholder': placeholder,
        'options': {
            "type": lookup_type,
            "asyncCallback": "$ctrl.getFormData",
            "map": {'valueProperty': mapping, 'nameProperty': 'name'}
        }
    }

    return result
997044
def get_form(self, request, obj=None, **kwargs):
        """"""

        template = get_template_from_request(request, obj)

        #model = create_page_model(get_placeholders(template))

        form = make_form(self.model, get_placeholders(template))

        # bound the form
        language = get_language_from_request(request)
        form.base_fields['language'].initial = language
        if obj:
            initial_slug = obj.slug(language=language, fallback=False)
            initial_title = obj.title(language=language, fallback=False)
            form.base_fields['slug'].initial = initial_slug
            form.base_fields['title'].initial = initial_title

        template = get_template_from_request(request, obj)
        page_templates = settings.get_page_templates()
        template_choices = list(page_templates)
        # is default template is not in the list add it
        if not [tpl for tpl in template_choices if tpl[0] == settings.PAGE_DEFAULT_TEMPLATE]:
            template_choices.insert(0, (settings.PAGE_DEFAULT_TEMPLATE,
                    _('Default template')))
        form.base_fields['template'].choices = template_choices
        form.base_fields['template'].initial = force_text(template)

        for placeholder in get_placeholders(template):
            ctype = placeholder.ctype
            if obj:
                initial = placeholder.get_content(obj, language, lang_fallback=False)
            else:
                initial = None
            form.base_fields[ctype] = placeholder.get_field(obj,
                language, initial=initial)

        return form
1175053
def template(self, data=None, settings=None):
        
        if settings is None:
            settings = {}
        ts = _.templateSettings
        _.defaults(ts, self.templateSettings)
        _.extend(settings, ts)

        # settings = {
        #     "interpolate": self.templateSettings.get('interpolate'),
        #     "evaluate": self.templateSettings.get('evaluate'),
        #     "escape": self.templateSettings.get('escape')
        # }

        _.extend(settings, {
            "escaper": r"\\|'|\r|\n|\t|\u2028|\u2029",
            "unescaper": r"\\(\\|'|r|n|t|u2028|u2029)"
        })

        src = self.obj
        #src = re.sub('"', r'\"', src)
        #src = re.sub(r'\\', r"\\", src)
        ns = self.Namespace()
        ns.indent_level = 1

        def unescape(code):
            def unescapes(matchobj):
                a = re.sub("^[\'\"]|[\'\"]$", "", ("%r" % matchobj.group(1)))
                # Python doesn't accept \n as a key
                if a == '\n':
                    a = "bn"
                if a == '\r':
                    a = "br"
                if a == '\t':
                    a = "bt"
                if a == '\u2028':
                    a = 'bu2028'
                if a == '\u2029':
                    a = 'bu2029'
                return self.escapes[a]
            return re.sub(settings.get('unescaper'), unescapes, code)

        def escapes(matchobj):
            a = matchobj.group(0)
            # Python doesn't accept \n as a key
            if a == '\n':
                a = "bn"
            if a == '\r':
                a = "br"
            if a == '\t':
                a = "bt"
            if a == '\u2028':
                a = 'bu2028'
            if a == '\u2029':
                a = 'bu2029'
            return '\\' + self.escapes[a]

        def indent(n=None):
            if n is not None:
                ns.indent_level += n
            return "  " * ns.indent_level

        def interpolate(matchobj):
            if getattr(str, 'decode', False):
                key = (matchobj.group(1).decode('string-escape')).strip()
            else:
                key = (bytes(matchobj.group(1), "utf-8").decode()).strip()
            return "' + str(" + unescape(key) + " or '') + '"

        def evaluate(matchobj):
            if getattr(str, 'decode', False):
                code = (matchobj.group(1).decode('string-escape')).strip()
            else:
                code = (bytes(matchobj.group(1), "utf-8").decode()).strip()
            if code.startswith("end"):
                return "')\n" + indent(-1) + "ns.__p += ('"
            elif code.endswith(':'):
                return "')\n" + indent() + unescape(code) + \
                       "\n" + indent(+1) + "ns.__p += ('"
            else:
                return "')\n" + indent() + unescape(code) + \
                       "\n" + indent() + "ns.__p += ('"

        def escape(matchobj):
            if getattr(str, 'decode', False):
                key = (matchobj.group(1).decode('string-escape')).strip()
            else:
                key = (bytes(matchobj.group(1), "utf-8").decode()).strip()
            return "' + _.escape(str(" + unescape(key) + " or '')) + '"

        source = indent() + 'class closure(object):\n    pass' + \
                            ' # for full closure support\n'
        source += indent() + 'ns = closure()\n'
        source += indent() + "ns.__p = ''\n"
        #src = re.sub("^[\'\"]|[\'\"]$", "", ("%r" % src))
        src = re.sub(settings.get("escaper"), escapes, src)
        source += indent() + "ns.__p += ('" + \
            re.sub(settings.get('escape'), escape, src) + "')\n"
        source = re.sub(settings.get('interpolate'), interpolate, source)
        source = re.sub(settings.get('evaluate'), evaluate, source)

        if getattr(str, 'decode', False):
            source += indent() + 'return ns.__p.decode("string_escape")\n'
        else:
            source += indent() + 'return bytes(ns.__p, "utf-8").decode()\n'

        f = self.create_function(settings.get("variable")
                                 or "obj=None", source)

        if data is not None:
            return f(data)
        return f
1188190
function genTemplateData() {
			var templateData = {
				data : {
					process : process,
					commit : commit,
					env : commitTask.commitOpts,
					options : options
				}
			};
			var rtn = {};
			var arr = Array.prototype.slice.call(arguments, 0);
			arr.forEach(function genIntMsgs(s) {
				rtn[s] = options[s] ? rbot.processTemplate(options[s], templateData) : '';
				if (rtn[s]) {
					rbot.log.verbose(s + ' = ' + rtn[s]);
				}
			});
			return rtn;
		}
4405
function prepareTemplates(templates){
  var valueGeneratorsDict = {
    select: function(obj){
      var types = {
        random:function(){
          return obj.choice[Math.floor(Math.random() * obj.choice.length)];
        },
        liner: function(){
          var el = obj.choice.shift();
          obj.choice.push(el);
          return el;
        },
        random_unique: function(){
          function shuffle(o) {
            for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
            return o;
          };
          if(!obj.randomized){obj.randomized = shuffle(obj.choice.slice());}
          var el = obj.randomized.shift();
          if(el===undefined){
            log.notEnoughChoice('random_unique','choice');
            process.exit()
          }
          return el;
        }
      }
      if(!types[obj.type]){
        return log.noTemplateType('select', obj.type, Object.keys(types))
      }
      return types[obj.type]
    },
    lipsum: function(obj){
      if(!(obj.max_char_length&&obj.min_char_length)){
        return log.missingSettings('lipsum', '', ['max_char_length','mim_char_length'])
      }
      var lorem = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'
      return function(){
        var chars = Math.floor(Math.random()*(obj.max_char_length-obj.min_char_length)+obj.min_char_length)
        var str = lorem.slice(0, chars)
        while(str.length < chars){
          var len = chars - str.length
          str += ' '+lorem.slice(0, len)
        }
        return str
      }
    },
    number: function(obj){
      var types = {
        random:function(){
          return Math.floor(Math.random()*(obj.max_num-obj.min_num)+obj.min_num);
        },
        incremental: function(){
          tempdata += obj.increments
          return tempdata;
        }
      }

      if(!types[obj.type]){
        return log.noTemplateType('number', obj.type, Object.keys(types))
      }
      if(obj.type == 'random' && !(obj.max_num&&obj.min_num)){
        return log.missingSettings('number', 'random', ['max_num','min_num'])
      }
      if(obj.type == 'incremental'){
        if(!(obj.starting_num&&obj.increments)){
          return log.missingSettings('number', 'incremental', ['starting_num','increments'])
        }
        var tempdata = this[obj.id] = obj.starting_num - obj.increments
      }

      return types[obj.type]
    },
    datetime: function(obj){
      var types = {
        random:function(){
          return output[obj.output_format](new Date(Math.floor(Math.random()*(max-min)+min)));
        },
        incremental: function(){
          tempdata += obj.increments
          return output[obj.output_format](new Date(tempdata));
        }
      }
      var output = {
        toString: function(d){ return d.toString(); },
        toDateString: function(d){ return d.toDateString(); },
        toISOString: function(d){ return d.toISOString(); },
        toJSON: function(d){ return d.toJSON(); },
        toGMTString: function(d){ return d.toGMTString(); },
        toLocaleDateString: function(d){ return d.toLocaleDateString(); },
        toLocaleString: function(d){ return d.toLocaleString(); },
        toLocaleTimeString: function(d){ return d.toLocaleTimeString(); },
        toTimeString: function(d){ return d.toTimeString(); },
        toUTCString: function(d){ return d.toUTCString(); },
        toYMDString:function(d){
          return d.toJSON().split('T')[0]
        }
      }

      if(!types[obj.type]){
        return log.noTemplateType('date', obj.type, Object.keys(types))
      }
      if(obj.type == 'random'){
        if(!(obj.max_datetime&&obj.min_datetime&&obj.output_format)){
          return log.missingSettings('date', 'random', ['max_datetime','min_datetime','output_format'])
        }
        var min = Date.parse(obj.min_datetime)
        var max = Date.parse(obj.max_datetime)
        if(isNaN(min)){
          return log.notParseableDatetime('min_datetime', obj.min_datetime)
        }else if(isNaN(max)){
          return log.notParseableDatetime('max_datetime', obj.max_datetime)
        }
      }
      if(obj.type == 'incremental'){
        if(!(obj.starting_datetime&&obj.increments&&obj.output_format)){
          return log.missingSettings('number', 'incremental', ['starting_datetime','increments','output_format'])
        }
        var tempdata = this[obj.id] = Date.parse(obj.starting_datetime) - obj.increments
        if(isNaN(tempdata)){
          return log.notParseableDatetime('starting_datetime', obj.starting_datetime)
        }
      }

      return types[obj.type]
    }
  }

  /*
  Recursively iterate each key in template object to find `stub_type` key.
  If the object has `stub_type` key, replace itself with corresponding
  function in valueGenerators valid
  Arg:
    - obj (Object)
  */
  function parseTemplate(obj) {
    for (var key in obj) {
      if (obj[key] !== null && typeof(obj[key])=="object") {
        if(obj[key].stub_type){
          if(!valueGeneratorsDict[obj[key].stub_type]){
            log.stubTypeNotFound(obj[key].stub_type)
          }else{
            obj[key].id = crypto.randomBytes(16).toString('hex');
            obj[key] = valueGeneratorsDict[obj[key].stub_type](obj[key])
          }
        }else{
          parseTemplate(obj[key]);
        }
      }
    }
  }

  if(templates){
    Object.keys(templates).map(function(t){
      parseTemplate(templates[t]);
    })
    return templates;
  }else{
    return [];
  }
}
1094377
def _keygen(self, event, ts=None):
        
        return "%s:%s" % (self.namespace(ts or time.time()), event)
321470
def generated_key(key):
    """"""
    key_name = key['name']
    if key['method'] == 'uuid':
        LOG.debug("Setting %s to a uuid", key_name)
        return str(uuid4())
    elif key['method'] == 'words':
        LOG.debug("Setting %s to random words", key_name)
        return random_word()
    elif key['method'] == 'static':
        if 'value' not in key.keys():
            raise aomi.exceptions.AomiData("Missing static value")

        LOG.debug("Setting %s to a static value", key_name)
        return key['value']
    else:
        raise aomi.exceptions.AomiData("Unexpected generated secret method %s"
                                       % key['method'])
782880
function parseObject(object) {
  const children = Object.keys(object).map(key => ({
    keyTemplate: parseString(key),
    valueTemplate: parse(object[key])
  }));
  const templateParameters = children.reduce(
    (parameters, child) =>
      parameters.concat(child.valueTemplate.parameters, child.keyTemplate.parameters),
    []
  );
  const templateFn = context => {
    return children.reduce((newObject, child) => {
      newObject[child.keyTemplate(context)] = child.valueTemplate(context);
      return newObject;
    }, {});
  };

  return Template(templateFn, templateParameters);
}
61125
@Override
    public String buildEditForm() {

        CmsMessages messages = Messages.get().getBundle(getLocale());
        StringBuffer retValue = new StringBuffer(2048);

        // check if the properties are editable
        boolean editable = isEditable();
        // create "disabled" attribute if properties are not editable
        String disabled = "";
        if (!editable) {
            disabled = " disabled=\"disabled\"";
        }

        retValue.append("<table border=\"0\">\n");
        retValue.append("<tr>\n");
        retValue.append("\t<td class=\"textbold\">" + messages.key(Messages.GUI_INPUT_PROPERTY_0) + "</td>\n");
        retValue.append("\t<td class=\"textbold\">" + messages.key(Messages.GUI_LABEL_VALUE_0) + "</td>\n");
        retValue.append(
            "\t<td class=\"textbold\" style=\"white-space: nowrap;\">"
                + messages.key(Messages.GUI_INPUT_USEDPROPERTY_0)
                + "</td>\n");
        retValue.append("</tr>\n");
        retValue.append("<tr><td><span style=\"height: 6px;\"></span></td></tr>\n");

        // create template select box row
        retValue.append(buildTableRowStart(messages.key(Messages.GUI_INPUT_TEMPLATE_0)));
        retValue.append(
            buildSelectTemplates(
                "name=\"" + CmsPropertyDefinition.PROPERTY_TEMPLATE + "\" class=\"maxwidth noborder\"" + disabled));
        retValue.append("</td>\n");
        retValue.append("\t<td class=\"textcenter\">");
        retValue.append("&nbsp;");
        retValue.append(buildTableRowEnd());

        // create the text property input rows
        retValue.append(buildTextInput(editable));

        // show navigation properties if enabled in explorer type settings
        if (showNavigation()) {
            retValue.append(buildNavigationProperties(editable));
        }

        retValue.append("</table>");

        return retValue.toString();
    }
746765
def get_template_setting(template_key, default=None):
    
    templates_var = getattr(settings, 'TEMPLATES', None)
    if templates_var:
        for tdict in templates_var:
            if template_key in tdict:
                return tdict[template_key]
    return default
178617
def inputindexbytemplate(project, user, inputtemplate):
        """"""
        index = [] #pylint: disable=redefined-outer-name
        prefix = Project.path(project, user) + 'input/'
        for linkf, f in globsymlinks(prefix + '.*.INPUTTEMPLATE.' + inputtemplate.id + '.*'):
            seq = int(linkf.split('.')[-1])
            index.append( (seq,f) )

        #yield CLAMFile objects in proper sequence
        for seq, f in sorted(index):
            yield seq, clam.common.data.CLAMInputFile(Project.path(project, user), f[len(prefix):])
1138416
def template(cls, address=None, commandtuple=None,
                 userdata=None, cmd2=-1, flags=None, acknak=None):
        """"""
        msgraw = bytearray([0x02, cls._code])
        msgraw.extend(bytes(cls._receivedSize))
        msg = ExtendedSend.from_raw_message(msgraw)

        if commandtuple:
            cmd1 = commandtuple.get('cmd1')
            cmd2out = commandtuple.get('cmd2')
        else:
            cmd1 = None
            cmd2out = None

        if cmd2 is not -1:
            cmd2out = cmd2

        msg._address = Address(address)
        msg._messageFlags = MessageFlags(flags)
        msg._messageFlags.extended = 1
        msg._cmd1 = cmd1
        msg._cmd2 = cmd2out
        msg._userdata = Userdata.template(userdata)
        msg._acknak = acknak
        return msg
509475
def process_form(self, instance, field, form, empty_marker=None,
                     emptyReturnsMarker=False):
        

        # a poor workaround for Plone repeating itself.
        # XXX this is important XXX
        key = field.getName() + '_value'
        if key in instance.REQUEST:
            return instance.REQUEST[key], {}
        value = form.get(field.getName(), empty_marker)
        # When a recordswidget's visibility is defined as hidden
        # '...visible={'view': 'hidden', 'edit': 'hidden'},...' the template
        # displays it as an input field with the attribute 'value' as a string
        # 'value="[{:},{:}]"'. This makes the system save the content of the
        # widget as the string instead of a dictionary inside a list, so we
        # need to check if the variable contains a python object as a string.
        if value and value is not empty_marker and isinstance(value, str):
            import ast
            try:
                value = ast.literal_eval(form.get(field.getName()))
            except:
                # cannot resolve string as a list!
                return empty_marker

        if not value:
            return value, {}
        if value is empty_marker:
            return empty_marker
        if emptyReturnsMarker and value == '':
            return empty_marker

        # we make sure that empty "value" inputs are saved as "" empty string.
        for i in range(len(value)):
            value[i] = dict(value[i])
            if 'value' not in value[i]:
                value[i]['value'] = ''

        instance.REQUEST[key] = value
        return value, {}
369306
def generate(template_name, object_binding)
      erb = ERB.new(File.read(File.join(template_path, template_name)), nil, "<>")
      erb.result(object_binding)
    end
796623
def generate_license(template, context):
    
    out = StringIO()
    content = template.getvalue()
    for key in extract_vars(template):
        if key not in context:
            raise ValueError("%s is missing from the template context" % key)
        content = content.replace("{{ %s }}" % key, context[key])
    template.close()  # free template memory (when is garbage collected?)
    out.write(content)
    return out