Store client's selection of a new translation
3358
def selectlanguage(self, event):
        """"""

        self.log('Language selection event:', event.client, pretty=True)

        if event.data not in all_languages():
            self.log('Unavailable language selected:', event.data, lvl=warn)
            language = None
        else:
            language = event.data

        if language is None:
            language = 'en'

        event.client.language = language

        if event.client.config is not None:
            event.client.config.language = language
            event.client.config.save()
1074088
function indexTranslations() {
  const { translations = {} } = getComponentsSettings();

  return index({
    file: 'translations.js',
    config: {
      type: TYPE_TRANSLATIONS,
      config: translations,
    },
    defaultContent: 'export default null;\n',
    ...getIndexLogTranslations(TYPE_TRANSLATIONS),
  });
}
178397
def save(self):
        
        active_language = get_language()
        for (name, value) in self.cleaned_data.items():
            if name not in registry:
                name, code = name.rsplit('_modeltranslation_', 1)
            else:
                code = None
            setting_obj, created = Setting.objects.get_or_create(name=name)
            if settings.USE_MODELTRANSLATION:
                if registry[name]["translatable"]:
                    try:
                        activate(code)
                    except:
                        pass
                    finally:
                        setting_obj.value = value
                        activate(active_language)
                else:
                    # Duplicate the value of the setting for every language
                    for code in OrderedDict(settings.LANGUAGES):
                        setattr(setting_obj,
                                build_localized_fieldname('value', code),
                                value)
            else:
                setting_obj.value = value
            setting_obj.save()
1296992
def clean_translation(self):
        
        translation = self.cleaned_data['translation']

        if self.instance and self.instance.content_object:
            # do not allow string longer than translatable field
            obj = self.instance.content_object
            field = obj._meta.get_field(self.instance.field)
            max_length = field.max_length

            if max_length and len(translation) > max_length:
                raise forms.ValidationError(
                    _('The entered translation is too long. You entered '
                      '%(entered)s chars, max length is %(maxlength)s') % {
                        'entered': len(translation),
                        'maxlength': max_length,
                    }
                )
        else:
            raise forms.ValidationError(
                _('Can not store translation. First create all translation'
                  ' for this object')
            )
        return translation
642658
def _set_dict_translations(instance, dict_translations):
	

	# If class has no translatable fields get out
	if not hasattr(instance._meta, "translatable_fields"):
		return False

	# If we are in a site with one language there is no need of saving translations
	if site_is_monolingual():
		return False

	# Translatable fields
	translatable_fields = instance._meta.translatable_fields

	# For each translatable field and for each language (excluding default language), we have to see if there is
	# two dynamic fields:
	# - <attribute>_<language_code>: translated atribute in <language_code>.
	#   For example: name_fr, name_es, description_it, etc.
	# - <attribute>_is_fuzzy_<language_code>: is a provisional translation of <attribute> for language <language_code>.
	#   For example: name_is_fuzzy_fr, name_is_fuzzy_es, description_is_fuzzy_it, etc.
	for field in translatable_fields:
		for lang in settings.LANGUAGES:
			lang = lang[0]
			if lang != settings.LANGUAGE_CODE:
					
				# Translated field name
				trans_field = trans_attr(field,lang)
				# If translated field name is in the dict, we assign it to the object
				if dict_translations.has_key(trans_field):
					setattr(instance,trans_field,dict_translations[trans_field])
					
				# Is fuzzy attribute
				trans_isfuzzy = trans_is_fuzzy_attr(field,lang)
				# If "is fuzzy" name is in the dict, we assign it to the object
				if dict_translations.has_key(trans_isfuzzy):
					is_fuzzy_value = (dict_translations[trans_isfuzzy]=="1") or (dict_translations[trans_isfuzzy]==1)
					setattr(instance,trans_isfuzzy, is_fuzzy_value)
575429
def tr8n_translations_cache_tag(opts = {})
      html = []

      opts[:translations_element_id] ||= :tr8n_translations
      client_sdk_var_name = opts[:client_var_name] || :tr8nProxy

      default_source_url = "#{controller.controller_name}/#{controller.action_name}.js"
      source = Tr8n::TranslationSource.find_or_create(opts[:source] || default_source_url)

      if Tr8n::Config.enable_browser_cache?  
        # translations are loaded through a script
        js_source = "/tr8n/api/language/translate.js?cache=true&callback=Tr8n.SDK.Proxy.registerTranslationKeys&source=#{CGI.escape(source.source)}&t=#{source.updated_at.to_i}"
        html << "<script type='text/javascript' src='#{js_source}'></script>"
      else  
        # translations are embedded right into the page
        html << "<script>"

        keys = Tr8n::TranslationKey.where(["(id in (select distinct(translation_key_id) from tr8n_translation_key_sources where translation_source_id = ?))", source.id])
        translations = []
        keys.each_with_index do |tkey, index|
          trn = tkey.translate(Tr8n::Config.current_language, {}, {:api => true})
          translations << trn 
        end

        html << "Tr8n.SDK.Proxy.registerTranslationKeys(#{translations.to_json});"
        html << "</script>"
      end
        
      html.join('').html_safe
    end
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
        )
672244
def get_translations(self, status=None):
        '''
            
        '''
        if status is not None:
            result = self.api_call('translation/?status=%s' % status)
        else:
            result = self.api_call('translation/')
        if result.status_code == 200:
            translations_json = json.loads(result.content)["objects"]
            translations = [Translation(**tj) for tj in translations_json]
        else:
            log.critical(
                'Error status when fetching translation from server: {'
                '}!'.format(
                    result.status_code))
            translations = []
        return translations
837410
def import_translations(request, language):
	
	def _import_po_file(uploadedfile, lang):
		lines = []
		for line in uploadedfile:
			lines.append(line)
		num_lines = len(lines)
		
		prog_ctxt = re.compile(r"msgctxt\s+\"(?P<id>\d+)--(?P<model>\w+)--(?P<object_id>\d+)--(?P<field>\w+)\"")
		prog_msgid = re.compile(r"msgid\s+\"(?P<source_text>.+)\"$")
		prog_msgstr = re.compile(r"msgstr\s+(?P<trans>.+)")
		
		i = 0
		while i < num_lines:
			line = lines[i]
			result = prog_ctxt.match(line)
			if result:
				id = result.group("id")
				is_fuzzy = (lines[i-1] == "#, fuzzy\n")

				source_text = lines[i+1]
				translation_line = lines[i+2]

				# Traducción
				g = prog_msgstr.match(translation_line)
				if g is None:
					i += 1
					continue
				translation = g.group("trans").replace("msgstr","")[1:-1].replace("\\\"","\"").replace('\\\'','\'')
					
				# Obtención de la traducción a partir del id
				try:
					field_trans = FieldTranslation.objects.get(id=id)
				except FieldTranslation.DoesNotExist:
					source_text = source_text.replace("msgid","")[1:-1].replace("\\\"","\"").replace('\\\'','\'')
					source_md5 = hashlib.md5(source_text.encode("utf-8")).hexdigest()
					field_trans = FieldTranslation(model=result.group("model"), object_id=result.group("object_id"), field=result.group("field"), lang=lang, source_text=source_text, source_md5=source_md5)
					
				# Establecemos la traducción y si es fuzzy
				field_trans.translation = translation
				field_trans.is_fuzzy = is_fuzzy
				field_trans.save()
				#print translation
				#print is_fuzzy
				i += 4
			i += 1
	
	# Elimina traducciones que no estén asociadas a ningún objeto
	FieldTranslation.delete_orphan_translations()
	
	# Acceso obligatoriamente por POST
	if request.method != "POST":
		return HttpResponseRedirect(reverse("modeltranslation:admin_url"))
	
	form = ImportTranslationsForm(request.POST, request.FILES)
	if form.is_valid():
		_import_po_file(request.FILES['file'], language)
		#cache = TransCache.factory()
		#cache.clear()
		return HttpResponseRedirect(reverse("modeltranslation:view_all_url",args=(language,"all")))

	return HttpResponseRedirect(reverse("modeltranslation:admin_url"))
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
620917
def update(self, new_data: Dict[Text, Dict[Text, Text]]):
        

        for locale, data in new_data.items():
            if locale not in self.dict:
                self.dict[locale] = {}

            self.dict[locale].update(data)
166479
def translate(self):
        """"""
        visitor = CheckTranslator(self.document,
                                  contents=self.contents,
                                  filename=self.filename,
                                  ignore=self.ignore)
        self.document.walkabout(visitor)
        self.checkers += visitor.checkers
508462
def update_translations(condition=None):
		
		if condition is None:
			condition = {}

		# Number of updated translations
		num_translations = 0
		
		# Module caching
		FieldTranslation._init_module_cache()

		# Current languages dict
		LANGUAGES = dict(lang for lang in MODELTRANSLATION_LANG_CHOICES)
		if settings.LANGUAGE_CODE in LANGUAGES:
			del LANGUAGES[settings.LANGUAGE_CODE]

		# For each module, we are going to update the translations
		for key in FieldTranslation._modules.keys():
			module = FieldTranslation._modules[key]

			# Class of the module
			clsmembers = inspect.getmembers(sys.modules[key], inspect.isclass)
			for cls in clsmembers:
				cls = cls[1]

				# If the model has in Meta "translatable_fields", we insert this fields
				if hasattr(cls,"_meta") and not cls._meta.abstract and hasattr(cls._meta,"translatable_fields") and len(cls._meta.translatable_fields)>0:
					objects = cls.objects.filter(**condition)
					
					# For each object, language and field are updated
					for obj in objects:
						for lang in LANGUAGES.keys():
							for field in cls._meta.translatable_fields:
								if FieldTranslation.update(obj=obj, field=field, lang=lang, context=""):
									num_translations += 1
		return num_translations
525863
def update_blurb(state, locale, key, value, overwrite = false)
      id = key
      key = "projects:#{api_key}:#{state}_blurbs:#{key}"
      
      current_value = redis.sismember("projects:#{api_key}:#{state}_blurb_keys", id) ? JSON.parse(redis.get(key)) : {}
      phrase = Phrase.new(self, current_value)
      
      # A new value is only written if no previous translation was present, or overwriting is enabled.
      if overwrite || phrase[locale].text.nil?
        phrase[locale] = value
        
        redis.sadd "projects:#{api_key}:#{state}_blurb_keys", id
        redis.sadd "projects:#{api_key}:locales", locale
        redis.set key, phrase.to_hash.to_json
        redis.set "projects:#{api_key}:#{state}_blurbs_etag", Projects.random_key
      end
    end
521591
function replaceLocale(locale, translations) {
    return store.dispatch({
      type: "".concat(moduleName, "/replaceLocale"),
      locale: locale,
      translations: translations
    });
  }
764447
def _construct_form(self, i, **kwargs):
        
        if not settings.HIDE_LANGUAGE:
            self._construct_available_languages()

        form = super(TranslationFormSet, self)._construct_form(i, **kwargs)

        if settings.HIDE_LANGUAGE:
            form.instance.language_code = settings.DEFAULT_LANGUAGE
        else:
            language_code = form.instance.language_code

            if language_code:
                logger.debug(
                    u'Removing translation choice %s for instance %s'
                    u' in form %d', language_code, form.instance, i
                )

                self.available_languages.remove(language_code)

            else:
                initial_language_code = self._get_default_language()

                logger.debug(
                    u'Preselecting language code %s for form %d',
                    initial_language_code, i
                )

                form.initial['language_code'] = initial_language_code

        return form
647074
private void saveLocalization() {

        SortedProperties localization = new SortedProperties();
        for (Object itemId : m_container.getItemIds()) {
            Item item = m_container.getItem(itemId);
            String key = item.getItemProperty(TableProperty.KEY).getValue().toString();
            String value = item.getItemProperty(TableProperty.TRANSLATION).getValue().toString();
            if (!(key.isEmpty() || value.isEmpty())) {
                localization.put(key, value);
            }
        }
        m_keyset.updateKeySet(m_localizations.get(m_locale).keySet(), localization.keySet());
        m_localizations.put(m_locale, localization);

    }