Make translations link to the native locations

    for generators that may contain translated content
425220
def interlink_translated_content(generator):
    '''
    '''
    inspector = GeneratorInspector(generator)
    for content in inspector.all_contents():
        interlink_translations(content)
197825
def _extract_translations(self, domains):
        """"""
        for domain, options in domains.items():
            # Create the extractor
            extractor = babel_frontend.extract_messages()
            extractor.initialize_options()
            # The temporary location to write the `.pot` file
            extractor.output_file = options['pot']
            # Add the comments marked with 'tn:' to the translation file for translators to read. Strip the marker.
            extractor.add_comments = ['tn:']
            extractor.strip_comments = True
            # The directory where the sources for this domain are located
            extractor.input_paths = [options['source']]
            # Pass the metadata to the translator
            extractor.msgid_bugs_address = self.manager.args.contact
            extractor.copyright_holder = self.manager.args.copyright
            extractor.version = self.manager.args.version
            extractor.project = self.manager.args.project
            extractor.finalize_options()
            # Add keywords for lazy translation functions, based on their non-lazy variants
            extractor.keywords.update({
                'gettext_lazy': extractor.keywords['gettext'],
                'ngettext_lazy': extractor.keywords['ngettext'],
                '__': extractor.keywords['gettext'],  # double underscore for lazy
            })
            # Do the extraction
            _run_babel_command(extractor)
254202
def _translate(env, target=None, source=SCons.Environment._null, *args, **kw):
    
    if target is None: target = []
    pot = env.POTUpdate(None, source, *args, **kw)
    po = env.POUpdate(target, pot, *args, **kw)
    return po
957706
function findI18nKeysAndStrings(filePath) {
    const textContentRegEx = /data-i18n="(.*?)".*?>\s*(.*?)\s*</gs;
    const placeholderRegEx = /data-i18n-placeholder="(.*?)"(?:.*?placeholder="(.*?)")?/g;
    const phraseRegEx = /translatePhrase\('(.*?)'\)/g;

    // Get global variable
    const contents = fs.readFileSync(filePath).toString();

    /** @type {object} */
    const dict = {};

    let textMatch;
    while ((textMatch = textContentRegEx.exec(contents)) !== null) { // eslint-disable-line no-cond-assign
        const key = textMatch[1];
        const phrase = textMatch[2];
        dict[key] = phrase;
    }

    let placeholderMatch;
    while ((placeholderMatch = placeholderRegEx.exec(contents)) !== null) { // eslint-disable-line no-cond-assign
        const key = placeholderMatch[1];
        const phrase = placeholderMatch[2] || '- not found -';
        dict[key] = phrase;
    }

    let phraseMatch;
    while ((phraseMatch = phraseRegEx.exec(contents)) !== null) { // eslint-disable-line no-cond-assign
        const key = phraseMatch[1];
        const phrase = false;
        dict[key] = phrase;
    }

    return dict;
}
1297762
def translate_item(self, item_dict):
        """"""
        if not item_dict.get('title'):
            return None
        # Skip attachments
        if item_dict.get('{wp}post_type', None) == 'attachment':
            return None
        ret_dict = {}
        # slugify post title if no slug exists
        ret_dict['slug']= item_dict.get('{wp}post_name') or re.sub(item_dict['title'],' ','-')
        ret_dict['ID']= item_dict['guid']
        ret_dict['title']= item_dict['title']
        ret_dict['description']= item_dict['description']
        ret_dict['content']= item_dict['{content}encoded']
        # fake user object
        ret_dict['author']= {'username':item_dict['{dc}creator'],
                             'first_name':'',
                             'last_name':''}
        ret_dict['terms']= item_dict.get('terms')
        ret_dict['date']= self.convert_date(
            item_dict['pubDate'],
            fallback=item_dict.get('{wp}post_date','')
        )
        return ret_dict
558019
def extract_translations(self, string):
        """"""

        trans = []
        for t in Lexer(string.decode("utf-8"), None).tokenize():
            if t.token_type == TOKEN_BLOCK:
                if not t.contents.startswith(
                        (self.tranz_tag, self.tranzchoice_tag)):
                    continue

                is_tranzchoice = t.contents.startswith(
                    self.tranzchoice_tag +
                    " ")
                kwargs = {
                    "id": self._match_to_transvar(id_re, t.contents),
                    "number": self._match_to_transvar(number_re, t.contents),
                    "domain": self._match_to_transvar(domain_re, t.contents),
                    "locale": self._match_to_transvar(locale_re, t.contents),
                    "is_transchoice": is_tranzchoice, "parameters": TransVar(
                        [x.split("=")[0].strip() for x in properties_re.findall(t.contents) if x],
                        TransVar.LITERAL
                    ),
                    "lineno": t.lineno,
                }

                trans.append(Translation(**kwargs))
        return trans
686702
def _prepare_translations(self):
        
        if config.TRANSLATIONS in self.paths:
            LOGGER.info('Loading translations from %s',
                        self.paths[config.TRANSLATIONS])
            from tornado import locale
            locale.load_translations(self.paths[config.TRANSLATIONS])
            if config.DEFAULT_LOCALE in self._config:
                LOGGER.info('Setting default locale to %s',
                            self._config[config.DEFAULT_LOCALE])
                locale.set_default_locale(self._config[config.DEFAULT_LOCALE])
815133
def transform_source(text):
    ''''''
    toks = tokenize.generate_tokens(StringIO(text).readline)
    result = []
    where_clause = False
    for toktype, tokvalue, _, _, _ in toks:
        if toktype == tokenize.NAME and tokvalue == "where":
            where_clause = True
        elif where_clause and toktype == tokenize.DEDENT:
            where_clause = False
            continue

        if not where_clause:
            result.append((toktype, tokvalue))
    return tokenize.untokenize(result)
1346017
function addTextLocale(locale, body, options = {}) {
  const gt = new Gettext();
  const domain = 'messages';
  const {
    filter,
    gettextDefaultCharset = 'UTF-8',
  } = options;

  if (body.length > 0) {
    gt.addTranslations(locale, domain, po.parse(body, gettextDefaultCharset));
  }

  if (filter) {
    const filterAsync = Promise.promisify(filter);
    return filterAsync(gt, locale);
  }

  return Promise.resolve(gt.catalogs[locale] && gt.catalogs[locale][domain].translations);
}
1039081
function loadTranslation(localeFilePath) {
    if(typeof localeFilePath == "undefined"){
        messages = defaultMessages;
        return null;
    }
    let fp = path.join(__dirname, localeFilePath);
    messages = require('jsonfile').readFileSync("." + fp);
    return messages;
}
767763
def update_translations(self, project_id, file_path=None,
                            language_code=None, overwrite=False, fuzzy_trigger=None):
        
        return self._upload(
            project_id=project_id,
            updating=self.UPDATING_TRANSLATIONS,
            file_path=file_path,
            language_code=language_code,
            overwrite=overwrite,
            fuzzy_trigger=fuzzy_trigger
        )
1032387
def prepare_translations!
      stash.each do |locale, attrs|
        if attrs.any?
          translation = record.translations.find_by_locale(locale)
          translation ||= record.translations.build(:locale => locale)
          attrs.each{ |name, value| translation[name] = value }
        end
      end
      reset
    end
954438
def add_translations(
        self, module_name, translations_dir="translations", domain="messages"
    ):
        
        module = importlib.import_module(module_name)
        for path in (Path(p, translations_dir) for p in module.__path__):
            if not (path.exists() and path.is_dir()):
                continue

            if not os.access(str(path), os.R_OK):
                self.app.logger.warning(
                    "Babel translations: read access not allowed {}, skipping."
                    "".format(repr(str(path).encode("utf-8")))
                )
                continue

            self._translations_paths.append((str(path), domain))
59635
def localized_resources(type = :resources, *resources, &block)
      localizable_route = nil

      if @locales
        res = resources.clone

        options = res.extract_options!
        r = res.first

        resource = resource_from_params(type, r, options.dup)

        # Check for translated resource
        stored_locale = I18n.locale
        @locales.each do |locale|
          I18n.locale = locale
          localized_path = I18nRouting.translation_for(resource.name, type)

          # A translated route exists :
          if !localized_path.blank? and String === localized_path
            puts("[I18n] > localize %-10s: %40s (%s) => /%s" % [type, resource.name, locale, localized_path]) if @i18n_verbose
            opts = options.dup
            opts[:path] = localized_path
            opts[:controller] ||= r.to_s.pluralize

            resource = resource_from_params(type, r, opts.dup)

            res = ["#{I18nRouting.locale_escaped(locale)}_#{r}".to_sym, opts]

            constraints = opts[:constraints] ? opts[:constraints].dup : {}
            constraints[:i18n_locale] = locale.to_s

            scope(:constraints => constraints, :path_names => I18nRouting.path_names(resource.name, @scope)) do
              localized_branch(locale) do
                send(type, *res) do

                  # In the resource(s) block, we need to keep and restore some context :
                  if block
                    old_name = @scope[:i18n_real_resource_name]
                    old = @scope[:scope_level_resource]

                    @scope[:i18n_real_resource_name] = resource.name
                    @scope[:i18n_scope_level_resource] = old
                    @scope[:scope_level_resource] = resource

                    if type == :resource and @scope[:name_prefix]
                      # Need to fake name_prefix for singleton resource
                      @scope[:name_prefix] = @scope[:name_prefix].gsub(Regexp.new("#{old.name}$"), resource.name)
                    end

                    block.call if block

                    @scope[:scope_level_resource] = old
                    @scope[:i18n_real_resource_name] = old_name
                  end

                  @scope[:i18n_scope_level_resource] = nil

                end
              end
            end

            localizable_route = resource
          end
        end
        I18n.locale = stored_locale
      end
      return localizable_route
    end
310829
def generate_localized_events(generator):
    

    if "i18n_subsites" in generator.settings["PLUGINS"]:
        if not os.path.exists(generator.settings['OUTPUT_PATH']):
            os.makedirs(generator.settings['OUTPUT_PATH'])

        for e in events:
            if "lang" in e.metadata:
                localized_events[e.metadata["lang"]].append(e)
            else:
                log.debug("event %s contains no lang attribute" % (e.metadata["title"],))
68776
def link_source_files(generator):
    
    # Get all attributes from the generator that are articles or pages
    posts = [
        getattr(generator, attr, None) for attr in PROCESS
        if getattr(generator, attr, None) is not None]
    # Work on each item
    for post in posts[0]:
        if not 'SHOW_SOURCE_ON_SIDEBAR' in generator.settings and \
            not 'SHOW_SOURCE_IN_SECTION' in generator.settings:
            return
        # Only try this when specified in metadata or SHOW_SOURCE_ALL_POSTS
        # override is present in settings
        if 'SHOW_SOURCE_ALL_POSTS' in generator.settings or \
            'show_source' in post.metadata:
            # Source file name can be optionally set in config
            show_source_filename = generator.settings.get(
                'SHOW_SOURCE_FILENAME', '{}.txt'.format(post.slug)
                )
            try:
                # Get the full path to the original source file
                source_out = os.path.join(
                    post.settings['OUTPUT_PATH'], post.save_as
                    )
                # Get the path to the original source file
                source_out_path = os.path.split(source_out)[0]
                # Create 'copy to' destination for writing later
                copy_to = os.path.join(
                    source_out_path, show_source_filename
                    )
                # Add file to published path
                source_url = urljoin(
                    post.save_as, show_source_filename
                    )
            except Exception:
                return
            # Format post source dict & populate
            out = dict()
            out['copy_raw_from'] = post.source_path
            out['copy_raw_to'] = copy_to
            logger.debug('Linked %s to %s', post.source_path, copy_to)
            source_files.append(out)
            # Also add the source path to the post as an attribute for tpls
            post.show_source_url = source_url
1037677
def export_translations(request, language):
	
	FieldTranslation.delete_orphan_translations()
	translations = FieldTranslation.objects.filter(lang=language)
	for trans in translations:
		trans.source_text = trans.source_text.replace("'","\'").replace("\"","\\\"")
		trans.translation = trans.translation.replace("'","\'").replace("\"","\\\"")
	replacements = {"translations":translations, "lang":language}
	if len(settings.ADMINS)>0:
		replacements["last_translator"] = settings.ADMINS[0][0]
		replacements["last_translator_email"] = settings.ADMINS[0][1]
	if settings.WEBSITE_NAME:
		replacements["website_name"] = settings.WEBSITE_NAME
	response = render(request=request, template_name='modeltranslation/admin/export_translations.po', dictionary=replacements, context_instance=RequestContext(request), content_type="text/x-gettext-translation")
	response['Content-Disposition'] = 'attachment; filename="{0}.po"'.format(language)
	return response