[START translate_get_glossary_beta]
497630
static Glossary getGlossary(String projectId, String location, String name) {
    try (TranslationServiceClient translationServiceClient = TranslationServiceClient.create()) {

      GlossaryName glossaryName =
          GlossaryName.newBuilder()
              .setProject(projectId)
              .setLocation(location)
              .setGlossary(name)
              .build();

      // Call the API
      Glossary response = translationServiceClient.getGlossary(glossaryName.toString());
      System.out.format("Got: %s\n", response.getName());
      return response;

    } catch (Exception e) {
      throw new RuntimeException("Couldn't create client.", e);
    }
  }
69041
def get_translation(modname, dirname=None):
    """"""
    if dirname is None:
        dirname = modname

    def translate_dumb(x):
        """Dumb function to not use translations."""
        if not is_unicode(x):
            return to_text_string(x, "utf-8")
        return x

    locale_path = get_module_data_path(dirname, relpath="locale",
                                       attr_name='LOCALEPATH')

    # If LANG is defined in Ubuntu, a warning message is displayed,
    # so in Unix systems we define the LANGUAGE variable.
    language = load_lang_conf()
    if os.name == 'nt':
        # Trying to set LANG on Windows can fail when Spyder is
        # run with admin privileges.
        # Fixes issue 6886
        try:
            os.environ["LANG"] = language      # Works on Windows
        except Exception:
            return translate_dumb
    else:
        os.environ["LANGUAGE"] = language  # Works on Linux
 
    import gettext
    try:
        _trans = gettext.translation(modname, locale_path, codeset="utf-8")
        lgettext = _trans.lgettext
        def translate_gettext(x):
            if not PY3 and is_unicode(x):
                x = x.encode("utf-8")
            y = lgettext(x)
            if is_text_string(y) and PY3:
                return y
            else:
                return to_text_string(y, "utf-8")
        return translate_gettext
    except Exception:
        return translate_dumb
963785
def call(word, opts)
      validate_opts!(opts)
      driver = Smartdict::Core::DriverManager.find(opts[:driver])

      translation_model = Models::Translation.find(word, opts[:from_lang], opts[:to_lang], opts[:driver])
      unless translation_model
        translation = driver.translate(word, opts[:from_lang], opts[:to_lang])
        translation_model = Models::Translation.create_from_struct(translation)
      end
      log_query(translation_model) if opts[:log]
      translation_model.to_struct
    end
470823
private function get_installed_translations( $module_type, $slug ) {
            if ( function_exists( 'wp_get_installed_translations' ) ) {
                return wp_get_installed_translations( $module_type );
            }

            $dir = "/{$module_type}";

            if ( ! is_dir( WP_LANG_DIR . $dir ) )
                return array();

            $files = scandir( WP_LANG_DIR . $dir );
            if ( ! $files )
                return array();

            $language_data = array();

            foreach ( $files as $file ) {
                if ( 0 !== strpos( $file, $slug ) ) {
                    continue;
                }

                if ( '.' === $file[0] || is_dir( WP_LANG_DIR . "{$dir}/{$file}" ) ) {
                    continue;
                }

                if ( substr( $file, -3 ) !== '.po' ) {
                    continue;
                }

                if ( ! preg_match( '/(?:(.+)-)?([a-z]{2,3}(?:_[A-Z]{2})?(?:_[a-z0-9]+)?).po/', $file, $match ) ) {
                    continue;
                }

                if ( ! in_array( substr( $file, 0, -3 ) . '.mo', $files ) )  {
                    continue;
                }

                list( , $textdomain, $language ) = $match;

                if ( '' === $textdomain ) {
                    $textdomain = 'default';
                }

                $language_data[ $textdomain ][ $language ] = wp_get_pomo_file_data( WP_LANG_DIR . "{$dir}/{$file}" );
            }

            return $language_data;
        }
1294348
def find_locales(self) -> Dict[str, gettext.GNUTranslations]:
        
        translations = {}

        for name in os.listdir(self.path):
            if not os.path.isdir(os.path.join(self.path, name)):
                continue
            mo_path = os.path.join(self.path, name, 'LC_MESSAGES', self.domain + '.mo')

            if os.path.exists(mo_path):
                with open(mo_path, 'rb') as fp:
                    translations[name] = gettext.GNUTranslations(fp)
            elif os.path.exists(mo_path[:-2] + 'po'):
                raise RuntimeError(f"Found locale '{name} but this language is not compiled!")

        return translations
589061
def _get_translation(self, lang):
        """"""

        try:
            return self._translations[lang]
        except KeyError:
            # The fact that `fallback=True` is not the default is a serious design flaw.
            rv = self._translations[lang] = gettext.translation(self._domain, localedir=localedir, languages=[lang],
                                                                fallback=True)
            return rv
91820
private function get_translations() {
		return array(
			'searchLabel'               => __( 'What can we help you with?', 'wordpress-seo-premium' ),
			'searchErrorLabel'          => __( 'Your search timed out. Please double-check your internet connection and try again.', 'wordpress-seo-premium' ),
			'noResultsLabel'            => __( 'No results found for', 'wordpress-seo-premium' ),
			'contactLabel'              => __( 'Send a Message', 'wordpress-seo-premium' ),
			'attachFileLabel'           => __( 'Attach a file', 'wordpress-seo-premium' ),
			'attachFileError'           => __( 'The maximum file size is 10 MB', 'wordpress-seo-premium' ),
			'nameLabel'                 => __( 'Your Name', 'wordpress-seo-premium' ),
			'nameError'                 => __( 'Please enter your name', 'wordpress-seo-premium' ),
			'emailLabel'                => __( 'Email address', 'wordpress-seo-premium' ),
			'emailError'                => __( 'Please enter a valid email address', 'wordpress-seo-premium' ),
			'topicLabel'                => __( 'Select a topic', 'wordpress-seo-premium' ),
			'topicError'                => __( 'Please select a topic from the list', 'wordpress-seo-premium' ),
			'subjectLabel'              => __( 'Subject', 'wordpress-seo-premium' ),
			'subjectError'              => __( 'Please enter a subject', 'wordpress-seo-premium' ),
			'messageLabel'              => __( 'How can we help you?', 'wordpress-seo-premium' ),
			'messageError'              => __( 'Please enter a message', 'wordpress-seo-premium' ),
			'sendLabel'                 => __( 'Send', 'wordpress-seo-premium' ),
			'contactSuccessLabel'       => __( 'Message sent, thank you!', 'wordpress-seo-premium' ),
			'contactSuccessDescription' => __( 'Someone from Team Yoast will get back to you soon, normally within a couple of hours.', 'wordpress-seo-premium' ),
		);
	}
512579
def translate(self):
        """"""
        varnames = set()
        ident = self.ident
        funcnames = set([ident])

        arg_exprs = []
        for arg in self.args:
            subexprs, subvars, subfuncs = arg.translate()
            varnames.update(subvars)
            funcnames.update(subfuncs)

            # Create a subexpression that joins the result components of
            # the arguments.
            arg_exprs.append(ex_call(
                ast.Attribute(ex_literal(u''), 'join', ast.Load()),
                [ex_call(
                    'map',
                    [
                        ex_rvalue(str.__name__),
                        ast.List(subexprs, ast.Load()),
                    ]
                )],
            ))

        subexpr_call = ex_call(
            FUNCTION_PREFIX + ident,
            arg_exprs
        )
        return [subexpr_call], varnames, funcnames
351214
function xgettext (input, options, cb) {
  if (typeof options === 'function') {
    cb = options;
    options = {};
  }

  options = options || {};

  if (!input) {
    throw new Error('No input specified');
  }

  if (!options.language && typeof input === 'string') {
    throw new Error('Language is required');
  }

  options['output'] = options['output'] || 'messages.po';
  options.directory = options.directory || ['.'];
  options.keyword = options.keyword || [];
  options['from-code'] = options['from-code'] || 'utf8';
  options['force-po'] = options['force-po'] || false;
  options['join-existing'] = options['join-existing'] || false;

  if (typeof options.keyword === 'string') {
    options.keyword = [options.keyword];
  }

  if (typeof options.directory === 'string') {
    options.directory = [options.directory];
  }

  const parsers = {};
  const getParser = function (name, keywordSpec) {
    name = name.trim().toLowerCase();

    if (!parsers[name]) {
      const Parser = require(`gettext-${name}`);

      if (Object.keys(keywordSpec).length > 0) {
        parsers[name] = new Parser(keywordSpec);
      } else if (Parser.keywordSpec) {
        parsers[name] = new Parser(Parser.keywordSpec);
      } else {
        parsers[name] = new Parser();
      }
    }

    return parsers[name];
  };

  const keywordSpec = createKeywordSpec(options.keyword);
  const translations = Object.create(null);

  const parseTemplate = function (parser, template, linePrefixer) {
    const strings = parser.parse(template);

    for (const key in strings) {
      if (strings.hasOwnProperty(key)) {
        const msgctxt = strings[key].msgctxt || '';
        const context = translations[msgctxt] || (translations[msgctxt] = {});
        const msgid = strings[key].msgid || key;
        context[msgid] = context[msgid] || { msgid: msgid, comments: {} };

        if (msgctxt) {
          context[msgid].msgctxt = strings[key].msgctxt;
        }

        if (strings[key].plural) {
          context[msgid].msgid_plural = context[msgid].msgid_plural || strings[key].plural;
          context[msgid].msgstr = ['', ''];
        }

        if (!options['no-location']) {
          context[msgid].comments.reference = (context[msgid].comments.reference || '')
            .split('\n')
            .concat(strings[key].line.map(linePrefixer))
            .join('\n')
            .trim('\n');
        }
      }
    }
  };

  const output = function () {
    if (cb) {
      if (Object.keys(translations).length > 0 || options['force-po']) {
        let existing = {};
        const writeToStdout = options.output === '-' || options.output === '/dev/stdout';

        if (!writeToStdout && options['join-existing']) {
          try {
            fs.accessSync(options.output, fs.F_OK);
            existing = gt.po.parse(fs.readFileSync(options.output, {
              encoding: options['from-code']
            }));
          } catch (e) {
            // ignore non-existing file
          }

          mergeDeep(translations, existing.translations);
        }

        const po = gt.po.compile({
          charset: options['from-code'],
          headers: {
            'content-type': `text/plain; charset=${options['from-code']}`
          },
          translations: translations
        });

        if (writeToStdout) {
          cb(po);
        } else {
          fs.writeFile(options.output, po, err => {
            if (err) {
              throw err;
            }

            cb(po);
          });
        }
      } else {
        cb();
      }
    }
  };

  if (typeof input === 'string') {
    parseTemplate(
      getParser(options.language, keywordSpec),
      input,
      line => `standard input:${line}`
    );

    output();
  } else {
    const addPath = path => line => `${path}:${line}`;

    if (options['files-from']) {
      input = fs.readFileSync(options['files-from'], options['from-code'])
        .split('\n')
        .filter(line => line.trim().length > 0);
    }

    const files = options.directory.reduce(
      (result, directory) => result.concat(input.map(
        file => path.join(directory, file.replace(/\\/g, path.sep))
      )),
      []
    );

    async.parallel(files.map(function (file) {
      return function (cb) {
        fs.readFile(path.resolve(file), options['from-code'], (err, res) => {
          if (err) {
            throw err;
          }

          const extension = path.extname(file);
          const language = options.language || xgettext.languages[extension];

          if (!language) {
            throw new Error(`No language specified for extension '${extension}'.`);
          }

          parseTemplate(getParser(language, keywordSpec), res, addPath(file.replace(/\\/g, '/')));

          cb();
        });
      };
    }), output);
  }
}
4202
def translate_keyword_tokens( token )
      keywords = ["__LINE__", "__ENCODING__", "__FILE__", "BEGIN",   
                  "END", "alias", "and", "begin", "break", "case",
                  "class", "def", "defined?", "do", "else", "elsif",
                  "end", "ensure", "false", "for", "if", "in",
                  "module", "next", "nil", "not", "or", "redo",
                  "rescue", "retry", "return", "self", "super",
                  "then", "true", "undef", "unless", "until", 
                  "when", "while", "yield"]
      if keywords.include?( token.content )
        token.type = token.content.downcase.to_sym
        # Change the state if we match a keyword
        @expr_state = :beg
      end
      
      # A couple of exceptions      
      if token.content == "BEGIN"
        token.type = :begin_global 
        @expr_state = :beg
      elsif token.content == "END"
        token.type = :end_global 
        @expr_state = :beg
      end
      
      token
    end
688078
def translate(self) -> Optional[str]:
        """"""

        fallbacks = getattr(settings, 'LOCALIZED_FIELDS_FALLBACKS', {})

        language = translation.get_language() or settings.LANGUAGE_CODE
        languages = fallbacks.get(language, [settings.LANGUAGE_CODE])[:]
        languages.insert(0, language)

        for lang_code in languages:
            value = self.get(lang_code)
            if value:
                return value or None

        return None
643002
function translate(key, options, hasOwnOptions) {

			var lng = options.lng || 'auto';

			if (!translations[lng]) {
				translations[lng] = {};
			}

			if (!t) {
				translations[lng][key] = key;
			} else if (!translations[lng][key] || hasOwnOptions) {
				translations[lng][key] = t(key, options);
			}

		}
321729
def translate_url(context, language):
    
    try:
        request = context["request"]
    except KeyError:
        return ""
    view = resolve(request.path)
    current_language = translation.get_language()
    translation.activate(language)
    try:
        url = reverse(view.func, args=view.args, kwargs=view.kwargs)
    except NoReverseMatch:
        try:
            url_name = (view.url_name if not view.namespace
                        else '%s:%s' % (view.namespace, view.url_name))
            url = reverse(url_name, args=view.args, kwargs=view.kwargs)
        except NoReverseMatch:
            url_name = "admin:" + view.url_name
            url = reverse(url_name, args=view.args, kwargs=view.kwargs)
    translation.activate(current_language)
    if context['request'].META["QUERY_STRING"]:
        url += "?" + context['request'].META["QUERY_STRING"]
    return url
674252
public List<Translation> readAllTranslationsForKey(String appid, String locale, String key, Pager pager) {
		Map<String, Object> terms = new HashMap<>(2);
		terms.put("thekey", key);
		terms.put("locale", locale);
		return search.findTerms(appid, Utils.type(Translation.class), terms, true, pager);
	}
270967
function (lang) {
        if (lang == "es") {
            monthsAbbr = [
                'Ene',
                'Feb',
                'Mar',
                'Abr',
                'May',
                'Jun',
                'Jul',
                'Ago',
                'Sep',
                'Oct',
                'Nov',
                'Dic'
            ];

            monthsFull = [
                'Enero',
                'Febrero',
                'Marzo',
                'Abril',
                'Mayo',
                'Junio',
                'Julio',
                'Agosto',
                'Septiembre',
                'Octubre',
                'Noviembre',
                'Diciembre'
            ];

            daysAbbr = [
                'Dom',
                'Lun',
                'Mar',
                'Mie',
                'Jue',
                'Vie',
                'Sab'
            ];

            daysFull = [
                'Domingo',
                'Lunes',
                'Martes',
                'Miércoles',
                'Jueves',
                'Viernes',
                'Sábado'
            ];

            dayNames = {
                'do': 0,
                'dom': 0,
                'domingo': 0,
                'lu': 1,
                'lun': 1,
                'lunes': 1,
                'ma': 2,
                'mar': 2,
                'martes': 2,
                'mi': 3,
                'mie': 3,
                'miercoles': 3,
                'ju': 4,
                'jue': 4,
                'jueves': 4,
                'vi': 5,
                'vie': 5,
                'viernes': 5,
                'sa': 6,
                'sab': 6,
                'sabado': 6
            };
            monthsAll = monthsFull.concat(monthsAbbr);
            daysAll = [
                'do',
                'dom',
                'domingo',
                'lu',
                'lun',
                'lunes',
                'ma',
                'mar',
                'martes',
                'mi',
                'mie',
                'miércoles',
                'ju',
                'jue',
                'jueves',
                'vi',
                'vie',
                'viernes',
                'sa',
                'sab',
                'sábado'
            ];

            monthNames = {
                'ene': 0,
                'enero': 0,
                'feb': 1,
                'febrero': 1,
                'mar': 2,
                'marzo': 2,
                'abr': 3,
                'abril': 3,
                'may': 4,
                'mayo':4,
                'jun': 5,
                'junio': 5,
                'jul': 6,
                'julio': 6,
                'ago': 7,
                'agosto': 7,
                'sep': 8,
                'septiembre': 8,
                'oct': 9,
                'octubre': 9,
                'nov': 10,
                'noviembre': 10,
                'dic': 11,
                'diciembre': 11
            };
        } else if (lang == "fr") {
            monthsAbbr = [
                'Jan',
                'Fév',
                'Mar',
                'Avr',
                'Mai',
                'Jui',
                'Jul',
                'Aoû',
                'Sep',
                'Oct',
                'Nov',
                'Déc'
            ];

            monthsFull = [
                'Janvier',
                'Février',
                'Mars',
                'Avril',
                'Mai',
                'Juin',
                'Juillet',
                'Août',
                'Septembre',
                'Octobre',
                'Novembre',
                'Décembre'
            ];

            daysAbbr = [
                'Dim',
                'Lun',
                'Mar',
                'Mer',
                'Jeu',
                'Ven',
                'Sam'
            ];

            daysFull = [
                'Dimanchi',
                'Lundi',
                'Mardi',
                'Mercredi',
                'Jeudi',
                'Vendredi',
                'Samedi'
            ];

            dayNames = {
                'di': 0,
                'dim': 0,
                'dimanchi': 0,
                'lu': 1,
                'lun': 1,
                'lundi': 1,
                'ma': 2,
                'mar': 2,
                'mardi': 2,
                'me': 3,
                'mer': 3,
                'mercredi': 3,
                'je': 4,
                'jeu': 4,
                'jeudi': 4,
                've': 5,
                'ven': 5,
                'vendredi': 5,
                'sa': 6,
                'sam': 6,
                'samedi': 6
            };
            monthsAll = monthsFull.concat(monthsAbbr);
            daysAll = [
                'di',
                'dim',
                'dimanchi',
                'lu',
                'lun',
                'lundi',
                'ma',
                'mar',
                'mardi',
                'me',
                'mer',
                'mercredi',
                'je',
                'jeu',
                'jeudi',
                've',
                'ven',
                'vendredi',
                'sa',
                'sam',
                'samedi'
            ];

            monthNames = {
                'jan': 0,
                'janvier': 0,
                'fév': 1,
                'février': 1,
                'mar': 2,
                'mars': 2,
                'avr': 3,
                'avril': 3,
                'mai': 4,
                'jui': 5,
                'juin': 5,
                'jul': 6,
                'juillet': 6,
                'aoû': 7,
                'août': 7,
                'sep': 8,
                'septembre': 8,
                'oct': 9,
                'octobre': 9,
                'nov': 10,
                'novembre': 10,
                'déc': 11,
                'décembre': 11
            };
        } else if (lang == "pt-BR") {
            monthsAbbr = [
                'Jan',
                'Fev',
                'Mar',
                'Abr',
                'Mai',
                'Jun',
                'Jul',
                'Ago',
                'Set',
                'Out',
                'Nov',
                'Dez'
            ];

            monthsFull = [
                'Janeiro',
                'Fevereiro',
                'Março',
                'Abril',
                'Maio',
                'Junho',
                'Julho',
                'Agosto',
                'Setembro',
                'Outubro',
                'Novembro',
                'Dezembro'
            ];

            daysAbbr = [
                'Dom',
                'Seg',
                'Ter',
                'Qua',
                'Qui',
                'Sex',
                'Sab'
            ];

            daysFull = [
                'Domingo',
                'Segunda',
                'Terça',
                'Quarta',
                'Quinta',
                'Sexta',
                'Sábado'
            ];

            dayNames = {
                'do': 0,
                'dom': 0,
                'domingo': 0,
                'se': 1,
                'seg': 1,
                'segunda': 1,
                'te': 2,
                'ter': 2,
                'terca': 2,
                'qa': 3,
                'qua': 3,
                'quarta': 3,
                'qi': 4,
                'qui': 4,
                'quinta': 4,
                'se': 5,
                'sex': 5,
                'sexta': 5,
                'sa': 6,
                'sab': 6,
                'sabado': 6
            };
            monthsAll = monthsFull.concat(monthsAbbr);
            daysAll = [
                'do',
                'dom',
                'domingo',
                'se',
                'seg',
                'segunda',
                'te',
                'ter',
                'terça',
                'qa',
                'qua',
                'quarta',
                'qi',
                'qui',
                'quinta',
                'se',
                'sex',
                'sexta',
                'sa',
                'sab',
                'sábado'
            ];

            monthNames = {
                'jan': 0,
                'janeiro': 0,
                'fev': 1,
                'fevereiro': 1,
                'mar': 2,
                'março': 2,
                'abr': 3,
                'abril': 3,
                'mai': 4,
                'jun': 5,
                'junho': 5,
                'jul': 6,
                'julho': 6,
                'ago': 7,
                'agosto': 7,
                'set': 8,
                'setembro': 8,
                'out': 9,
                'outubro': 9,
                'nov': 10,
                'novembro': 10,
                'dez': 11,
                'dezembro': 11
            };
        }
    }
327881
static TranslateTextResponse translateTextWithGlossary(
      String projectId,
      String location,
      String name,
      String text,
      String sourceLanguageCode,
      String targetLanguageCode) {
    try (TranslationServiceClient translationServiceClient = TranslationServiceClient.create()) {

      LocationName locationName =
          LocationName.newBuilder().setProject(projectId).setLocation(location).build();
      GlossaryName glossaryName =
          GlossaryName.newBuilder()
              .setProject(projectId)
              .setLocation(location)
              .setGlossary(name)
              .build();
      TranslateTextGlossaryConfig translateTextGlossaryConfig =
          TranslateTextGlossaryConfig.newBuilder().setGlossary(glossaryName.toString()).build();
      TranslateTextRequest translateTextRequest =
          TranslateTextRequest.newBuilder()
              .setParent(locationName.toString())
              .setMimeType("text/plain")
              .setSourceLanguageCode(sourceLanguageCode)
              .setTargetLanguageCode(targetLanguageCode)
              .addContents(text)
              .setGlossaryConfig(translateTextGlossaryConfig)
              .build();

      // Call the API
      TranslateTextResponse response = translationServiceClient.translateText(translateTextRequest);
      System.out.format(
          "Translated text: %s", response.getTranslationsList().get(0).getTranslatedText());
      return response;

    } catch (Exception e) {
      throw new RuntimeException("Couldn't create client.", e);
    }
  }
231781
def translate(self):
        """"""
        ident = self.ident
        expr = ex_rvalue(VARIABLE_PREFIX + ident)
        return [expr], set([ident]), set()