<editor-fold defaultstate="collapsed" desc="Translation helper methods">
186549
private JCBlock makeLambdaBody(JCLambda tree, JCMethodDecl lambdaMethodDecl) {
        return tree.getBodyKind() == JCLambda.BodyKind.EXPRESSION ?
                makeLambdaExpressionBody((JCExpression)tree.body, lambdaMethodDecl) :
                makeLambdaStatementBody((JCBlock)tree.body, lambdaMethodDecl, tree.canCompleteNormally);
    }
1131353
@Override
    @GwtIncompatible("incompatible method")
    public int translate(final CharSequence input, final int index, final Writer out) throws IOException {
        for (final CharSequenceTranslator translator : translators) {
            final int consumed = translator.translate(input, index, out);
            if(consumed != 0) {
                return consumed;
            }
        }
        return 0;
    }
885294
private static String translateFormat(String formatString, Map<String, String> mapping, String escapeStart, String escapeEnd, String targetEscapeStart, String targetEscapeEnd) {
		int beginIndex = 0;
		int i = 0;
		char lastChar = 0;
		char currentChar = 0;
		String resultString = "";
		char esc1 = escapeStart.charAt(0);
		char esc2 = escapeEnd.charAt(0);

		for (; i < formatString.length(); i++) {
			currentChar = formatString.charAt(i);
			if (i > 0 && lastChar != currentChar) {
				resultString += mapSubformat(formatString, mapping, beginIndex, i, escapeStart, escapeEnd, targetEscapeStart, targetEscapeEnd);
				beginIndex = i;
			}
			lastChar = currentChar;
			if (currentChar == esc1) {
				i++;
				while (i< formatString.length() && formatString.charAt(i) != esc2) {
					i++;
				}
				resultString += targetEscapeStart;
				resultString += formatString.substring(beginIndex+1, i);
				resultString += targetEscapeEnd;
				i++;
				if (i < formatString.length()) {
					lastChar = formatString.charAt(i);
				}
				beginIndex = i;
			}
		}
		
		if (beginIndex < formatString.length() && i <= formatString.length()) {
			return resultString + mapSubformat(formatString, mapping, beginIndex, i, escapeStart, escapeEnd, targetEscapeStart, targetEscapeEnd);
		} else {
			return resultString;
		}

	}
1176511
static String[] translateCommandline(String toProcess) {
        if (toProcess == null || toProcess.length() == 0) {
            //no command? no string
            return new String[0];
        }
        // parse with a simple finite state machine

        final int normal = 0;
        final int inQuote = 1;
        final int inDoubleQuote = 2;
        int state = normal;
        final StringTokenizer tok = new StringTokenizer(toProcess, "\"\' ", true);
        final ArrayList<String> result = new ArrayList<String>();
        final StringBuilder current = new StringBuilder();
        boolean lastTokenHasBeenQuoted = false;

        while (tok.hasMoreTokens()) {
            String nextTok = tok.nextToken();
            switch (state) {
                case inQuote:
                    if ("\'".equals(nextTok)) {
                        lastTokenHasBeenQuoted = true;
                        state = normal;
                    } else {
                        current.append(nextTok);
                    }
                    break;
                case inDoubleQuote:
                    if ("\"".equals(nextTok)) {
                        lastTokenHasBeenQuoted = true;
                        state = normal;
                    } else {
                        current.append(nextTok);
                    }
                    break;
                default:
                    if ("\'".equals(nextTok)) {
                        state = inQuote;
                    } else if ("\"".equals(nextTok)) {
                        state = inDoubleQuote;
                    } else if (" ".equals(nextTok)) {
                        if (lastTokenHasBeenQuoted || current.length() != 0) {
                            result.add(current.toString());
                            current.setLength(0);
                        }
                    } else {
                        current.append(nextTok);
                    }
                    lastTokenHasBeenQuoted = false;
                    break;
            }
        }
        if (lastTokenHasBeenQuoted || current.length() != 0) {
            result.add(current.toString());
        }
        if (state == inQuote || state == inDoubleQuote) {
            throw new ParseException("unbalanced quotes in " + toProcess);
        }
        return result.toArray(new String[0]);
    }
333229
private Statement handleTranslationWithPlaceholders(
      MsgNode msg,
      ImmutableList<SoyPrintDirective> escapingDirectives,
      Expression soyMsgParts,
      Expression locale,
      MsgPartsAndIds partsAndId) {
    // We need to render placeholders into a buffer and then pack them into a map to pass to
    // Runtime.renderSoyMsgWithPlaceholders.

    Map<String, Function<Expression, Statement>> placeholderNameToPutStatement =
        new LinkedHashMap<>();
    putPlaceholdersIntoMap(msg, partsAndId.parts, placeholderNameToPutStatement);
    // sanity check
    checkState(!placeholderNameToPutStatement.isEmpty());
    ConstructorRef cstruct =
        msg.isPlrselMsg() ? ConstructorRef.PLRSEL_MSG_RENDERER : ConstructorRef.MSG_RENDERER;
    Statement initRendererStatement =
        variables
            .getCurrentRenderee()
            .putInstanceField(
                thisVar,
                cstruct.construct(
                    constant(partsAndId.id),
                    soyMsgParts,
                    locale,
                    constant(placeholderNameToPutStatement.size())));
    List<Statement> initializationStatements = new ArrayList<>();
    initializationStatements.add(initRendererStatement);
    for (Function<Expression, Statement> fn : placeholderNameToPutStatement.values()) {
      initializationStatements.add(fn.apply(variables.getCurrentRenderee().accessor(thisVar)));
    }

    Statement initMsgRenderer = Statement.concat(initializationStatements);
    Statement render;
    if (areAllPrintDirectivesStreamable(escapingDirectives)) {
      AppendableAndOptions wrappedAppendable =
          applyStreamingEscapingDirectives(
              escapingDirectives,
              appendableExpression,
              parameterLookup.getPluginContext(),
              variables);
      FieldRef currentAppendableField = variables.getCurrentAppendable();
      Statement initAppendable =
          currentAppendableField.putInstanceField(thisVar, wrappedAppendable.appendable());
      Expression appendableExpression = currentAppendableField.accessor(thisVar);
      Statement clearAppendable =
          currentAppendableField.putInstanceField(
              thisVar, constantNull(LOGGING_ADVISING_APPENDABLE_TYPE));
      if (wrappedAppendable.closeable()) {
        clearAppendable =
            Statement.concat(
                appendableExpression
                    .checkedCast(BytecodeUtils.CLOSEABLE_TYPE)
                    .invokeVoid(MethodRef.CLOSEABLE_CLOSE),
                clearAppendable);
      }
      render =
          Statement.concat(
              initAppendable,
              detachState.detachForRender(
                  variables
                      .getCurrentRenderee()
                      .accessor(thisVar)
                      .invoke(
                          MethodRef.SOY_VALUE_PROVIDER_RENDER_AND_RESOLVE,
                          appendableExpression,
                          // set the isLast field to true since we know this will only be rendered
                          // once.
                          /* isLast=*/ constant(true))),
              clearAppendable);
    } else {
      Label start = new Label();
      SoyExpression value =
          SoyExpression.forSoyValue(
              StringType.getInstance(),
              detachState
                  .createExpressionDetacher(start)
                  .resolveSoyValueProvider(variables.getCurrentRenderee().accessor(thisVar))
                  .checkedCast(SOY_STRING_TYPE));
      for (SoyPrintDirective directive : escapingDirectives) {
        value = parameterLookup.getRenderContext().applyPrintDirective(directive, value);
      }
      render =
          appendableExpression.appendString(value.unboxAsString()).toStatement().labelStart(start);
    }
    return Statement.concat(
        initMsgRenderer,
        render,
        // clear the field
        variables
            .getCurrentRenderee()
            .putInstanceField(
                thisVar,
                BytecodeUtils.constantNull(ConstructorRef.MSG_RENDERER.instanceClass().type())));
  }
37416
function(translateAttr, translationId, scope, interpolateParams, defaultTranslationText, translateNamespace) {
          if (translationId) {
            // if translation id starts with '.' and translateNamespace given, prepend namespace
            if (translateNamespace && translationId.charAt(0) === '.') {
              translationId = translateNamespace + translationId;
            }

            $translate(translationId, interpolateParams, translateInterpolation, defaultTranslationText, scope.translateLanguage)
              .then(function (translation) {
                applyTranslation(translation, scope, true, translateAttr);
              }, function (translationId) {
                applyTranslation(translationId, scope, false, translateAttr);
              });
          } else {
            // as an empty string cannot be translated, we can solve this using successful=false
            applyTranslation(translationId, scope, false, translateAttr);
          }
        }
605143
function translateElement(element, locale) {
    var $element = $(element),
        keyPath = $element.data('translate');

    var translation = getTranslation(keyPath, locale);
    if(translation) {
      $(element).text(translation);
    }
  }
649453
protected String resolveHelpText(Locale locale) {

        String helpText = getHelpText().key(locale);
        if ((getColumnForTexts() != null) && (getItem().get(getColumnForTexts()) != null)) {
            helpText = new MessageFormat(helpText, locale).format(new Object[] {getItem().get(getColumnForTexts())});
        }
        return helpText;
    }
880845
public static Grammar translate(Rule[] rules, StringArrayList symbolTable) throws ActionException {
        int i;
        Ebnf builder;
        Grammar tmp;
        Grammar buffer;
        int firstHelper;
        int lastHelper;

        firstHelper = symbolTable.size();
        buffer = new Grammar(rules[0].getLeft(), symbolTable);
        builder = new Ebnf(firstHelper);
        for (i = 0; i < rules.length; i++) {
            tmp = (Grammar) rules[i].getRight().visit(builder);
            buffer.addProduction(new int[]{rules[i].getLeft(), tmp.getStart()});
            buffer.addProductions(tmp);
            buffer.expandSymbol(tmp.getStart());
            buffer.removeProductions(tmp.getStart());
        }
        lastHelper = builder.getHelper() - 1;
        buffer.removeDuplicateSymbols(firstHelper, lastHelper);
        buffer.removeDuplicateRules();
        buffer.packSymbols(firstHelper, lastHelper + 1);
        return buffer;
    }
1309180
function Translator(api, options) {
  var origLength = JSON.stringify(api, null, 2).length;
  var debugInfo = {flattened: {}, pruned: {}};
  var shapeName = 'S0';
  var shapeNameMap = {};
  var visitedShapes = {};

  function logResults() {
    console.log('** Generated', api.metadata.endpointPrefix + '-' +
      api.metadata.apiVersion +'.min.json' +
      (process.env.DEBUG ? ':' : ''));

    if (process.env.DEBUG) {
      var pruned = Object.keys(debugInfo.pruned);
      var flattened = Object.keys(debugInfo.flattened);
      var newLength = JSON.stringify(api, null, 2).length;
      console.log('- Pruned Shapes:', pruned.length);
      console.log('- Flattened Shapes:', flattened.length);
      console.log('- Remaining Shapes:', Object.keys(api.shapes).length);
      console.log('- Original Size:', origLength / 1024.0, 'kb');
      console.log('- Minified Size:', newLength / 1024.0, 'kb');
      console.log('- Size Saving:', (origLength - newLength) / 1024.0, 'kb');
      console.log('');
    }
  }

  function deleteTraits(obj) {
    if (!options.documentation) {
      delete obj.documentation;
      delete obj.documentationUrl;
      delete obj.errors;
      delete obj.min;
      delete obj.max;
      delete obj.pattern;
      delete obj['enum'];
      delete obj.box;
    }
  }

  function trackShapeDeclaration(ref) {
    if (ref.shape && !shapeNameMap[ref.shape]) {
      // found a shape declaration we have not yet visited.
      // assign a new generated name in the shapeNameMap & visit it
      var oldShapeName = ref.shape;
      ref.shape = shapeName = nextString(shapeName);

      visitedShapes[shapeName] = api.shapes[oldShapeName];
      shapeNameMap[oldShapeName] = {name: shapeName, refs: [ref]};

      traverseShapeRef(api.shapes[oldShapeName]);
    } else if (ref.shape && shapeNameMap[ref.shape]) {
      // we visited this shape before. keep track of this ref and rename
      // the referenced declaration to the generated name
      var map = shapeNameMap[ref.shape];
      map.refs.push(ref);
      ref.shape = map.name;        
    }
  }

  function pruneShapes() {
    // prune shapes visited only once or only have type specifiers
    each(shapeNameMap, function(name, map) {
      if (Object.keys(visitedShapes[map.name]).join() === 'type' &&
          ['structure','map','list'].indexOf(visitedShapes[map.name].type) < 0) {
        // flatten out the shape (only a scalar type property is on the shape)
        for (var i = 0; i < map.refs.length; i++) {
          var ref = map.refs[i];
          debugInfo.flattened[name] = true;
          delete ref.shape;
          ref.type = visitedShapes[map.name].type;

          // string type is default, don't need to specify this
          if (ref.type === 'string') delete ref.type;
        }

        // we flattened all refs, we can prune the shape too
        delete visitedShapes[map.name];
        debugInfo.pruned[name] = true;
      } else if (map.refs.length === 1) { // only visited once
        // merge shape data onto ref
        var shape = visitedShapes[map.name];

        for (var i = 0; i < map.refs.length; i++) {
          delete map.refs[i].shape;
          for (var prop in shape) {
            if (shape.hasOwnProperty(prop)) {
              //Translator prefers timestampFormat trait in members rather than in shape
              if (map.refs[i].hasOwnProperty(prop) && ['timestampFormat'].indexOf(prop) >= 0) {
                continue;
              }
              map.refs[i][prop] = shape[prop];
            }
            
          }
        }

        // delete the visited shape
        delete visitedShapes[map.name];
        debugInfo.pruned[name] = true;
      }
    });
  }

  function traverseShapeRef(ref) {
    if (!ref) return;

    deleteTraits(ref);

    traverseShapeRef(ref.key); // for maps
    traverseShapeRef(ref.value); // for maps
    traverseShapeRef(ref.member); // for lists

    // for structures
    each(ref.members || {}, function(key, value) { traverseShapeRef(value); });

    // resolve shape declarations
    trackShapeDeclaration(ref);
  }

  function traverseOperation(op) {
    deleteTraits(op);

    delete op.name;
    if (op.http) {
      if (op.http.method === 'POST') delete op.http.method;
      if (op.http.requestUri === '/') delete op.http.requestUri;
      if (Object.keys(op.http).length === 0) delete op.http;
    }

    traverseShapeRef(op.input);
    traverseShapeRef(op.output);    
  }

  function traverseApi() {
    deleteTraits(api);
    each(api.operations, function(name, op) { traverseOperation(op); });
    api.shapes = visitedShapes;
  }

  traverseApi();
  pruneShapes();
  logResults();
  return api;
}
1204026
def append_translated(model, fields):
    ""
    fields = set(fields)
    from modeltranslation.translator import translator
    opts = translator.get_options_for_model(model)
    for key, translated in opts.fields.items():
        if key in fields:
            fields = fields.union(f.name for f in translated)
    return fields
1261009
function translateMessagesToBundle(src, translationsSrc) {
    var _ref = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];

    var _ref$inputFormat = _ref.inputFormat;
    var inputFormat = _ref$inputFormat === undefined ? 'po' : _ref$inputFormat;

    var options = _objectWithoutProperties(_ref, ['inputFormat']);

    var bundle = {};
    var missing = {};
    var translations = _io2.default[inputFormat].in(translationsSrc, options);

    function attemptToCreateRenderer(node, message) {
        if (translations[message]) {
            bundle[message] = (0, _translation2.default)(node, translations[message], message);
        } else {
            missing[message] = message;
        }
    }

    var plugin = function plugin() {
        return {
            visitor: {
                CallExpression: function CallExpression(_ref2) {
                    var node = _ref2.node;

                    if ((0, _ast.isFunctionMarker)(node)) {
                        var message = (0, _extract.extractFunctionMessage)(node);
                        attemptToCreateRenderer(node, message);
                    }
                },
                JSXElement: function JSXElement(_ref3) {
                    var node = _ref3.node;

                    if ((0, _ast.isElementMarker)(node)) {
                        var message = (0, _extract.extractElementMessageWithoutSideEffects)(node);
                        attemptToCreateRenderer(node, message);
                    }
                }
            }
        };
    };

    _parsing2.default.transform(src, [plugin]);

    return { bundle: bundle, missing: missing };
}
1004371
function translate(cldr, locale, opts) {
  if (typeof cldr === 'string') return augment(interpolate(cldr, opts));

  opts = opts || {};

  var pluralize = lookup(locale, cldr._format || opts.pluralFormat, plural);
  if (Array.isArray(cldr)) cldr = convertArray(cldr, pluralize, opts);

  validate(cldr, pluralize);

  var paramsObj = {};
  var cases = toFunctions(cldr, pluralize, opts, paramsObj);
  var paramsKeys = Object.keys(paramsObj);

  var key = cldr._plural_key ||
            opts.pluralKey ||
            discoverKey(paramsKeys,
                        opts.discoverableKeys || {'smart_count':1, 'count':1, 'length':1, 'items':1, 'total':1},
                        opts.defaultPluralKey || 'smart_count');

  var validatePluralKey = opts.validatePluralKey !== false;
  var silentValidation = !!opts.validatePluralSilent;
  var decimal = number.decimal[locale] || number.decimal.en;
  var toLocaleString = opts.toLocaleString !== false;

  return augment(function(params) {
    if (typeof params === 'number') params = convertSmartCount(params, key);

    var count = parseInt(params[key], 10);
    if (validatePluralKey && isNaN(count)) {
      if (silentValidation) return [];
      throw new Error('expected "' + key + '" to be a number. got "' + (typeof params[key]) + '".');
    }

    if (toLocaleString) params = formatNumbers(params, decimal);

    return (cases[count] || cases[pluralize(count || 0)])(params);
  }, paramsKeys);
}
460835
function WfI18n (translation = {}, fallback = null, locale = 'en') {
    this.translation = translation
    this.locale = locale
    this.fallback = fallback

    this.t = (key) => {
      let result = this.translation[this.locale]
      if (!result) { result = this.translation[this.fallback] }
      if (!result) { throw new WfException(`Translation for locale "${this.locale}" not found.`) }
      const keys = key.split('.')
      if (keys.length === 0) { throw new WfException('Empty translation key.') }
      for (let i = 0; i < keys.length; i++) {
        result = result[keys[i]]
        if (!result) {
          setTimeout(() => {
            throw new WfException(`Translation for key "${key}" not found.`)
          })
          return key
        }
      }
      return result
    }
    return {
      t: this.t
    }
  }
798553
public RuntimeException translate(String sql, List<Object> bindings, SQLException ex) {
        return exceptionTranslator.translate(sql, bindings, ex);
    }
207635
@Test
    public void get_missing_default_translation() {
        KeySearchCriteria criteria = new KeySearchCriteria(true, null, null, null);
        PaginatedView<KeyRepresentation> keyRepresentations = keyFinder
                .findKeysWithTheirDefaultTranslation(FIRST_RANGE, criteria);

        assertThat(keyRepresentations.getPageSize()).isEqualTo(2);

        KeyRepresentation representation = keyRepresentations.getView().get(0);
        assertThat(StringUtils.isBlank(representation.getTranslation())).isTrue();
    }
273210
function  {
  var defaultLocaleBundle, localeBundle, merged;
  var aux = {};

  init();

  // Load i18n content.
  loadCldr(defaultLocale);
  loadCldr(locale);

  defaultLocaleBundle = new Globalize(defaultLocale).cldr.attributes.bundle;
  localeBundle = new Globalize(locale).cldr.attributes.bundle;

  assertLocale(locale);
  assert(typeof translation === "object", "missing or invalid `translation` argument, JSON expected (e.g., {\"en\": ...})");
  assert(typeof defaultLocale === "string", "missing or invalid `defaultLocale` argument, String expected (e.g., \"en\")");

  aux[localeBundle] = generateDefaultTranslation(defaultLocale)[defaultLocaleBundle];
  merged = merge({}, aux, translation);
  if (orderedStringify(translation) !== orderedStringify(merged)) {
    return merged;
  }
}