Synchronises translations with transifex.com
541187
def translations(context: Context, pull=False, push=False):
    
    if not (pull or push):
        raise TaskError('Specify whether to push or pull translations')
    if pull:
        context.shell('tx', 'pull')
        make_messages(context, javascript=False)
        make_messages(context, javascript=True)
    if push:
        context.shell('tx', 'push', '--source', '--no-interactive')
302011
private function fetchTransifexResources($transifexProject)
    {
        $client = $this->getHttpClient();

        $response = $client
            ->setUri("https://www.transifex.com/api/2/project/$transifexProject/resources/")
            ->setMethod('GET')
            ->send()
        ;
        if ($response->getStatusCode() < 200 || $response->getStatusCode() >= 300) {
            throw new Exception($response->getReasonPhrase());
        }
        $rawResources = @json_decode($response->getBody(), true);
        if (!is_array($rawResources)) {
            throw new Exception('Failed to decode response');
        }

        $result = [];
        foreach ($rawResources as $rawResource) {
            $result[] = $rawResource['slug'];
        }

        sort($result);

        return $result;
    }
890515
function translate (content, contentTypes) {
  let output = {}
  content.forEach(each => {
    const base = path.parse(each.file).base
    if (base === 'index.md') {
      const type = each.dir.split('/').pop()
      const contentTypeTranslation = contentTypes.find(contentType => contentType[type])
      if (contentTypeTranslation && contentTypeTranslation[type]) {
        output[type] = contentTypeTranslation[type](content, type)
      }
    }
  })
  return output
}
1230849
function synchronize() {

		$tCounter = 0;

		if ($this->changed) {
			$tFile = fopen ( $this->fileName, 'a' );

			while ( ! flock ( $tFile, LOCK_EX ) ) {
				usleep ( 5 );
				$tCounter ++;
				if ($tCounter == 100) {
					return false;
				}
			}

			$tContent = serialize ( $this->elements );

			ftruncate ( $tFile, 0 );

			if ($this->useZip) {
				$tContent = gzcompress ( $tContent );
			}

			fputs ( $tFile, $tContent );

			flock ( $tFile, LOCK_UN );
			fclose ( $tFile );
			return true;
		}
			
		return true;
	}
71636
def sync_it_now
      puts "Attempt Sync"

      # Getting the last sync value.
      last_update_at = get_last_update_at

      # querying the page.
      page = @mechanize_agent.get("#{ChronuscopClient.configuration_object.chronuscop_server_address}/projects/#{ChronuscopClient.configuration_object.project_number}/translations.xml/?auth_token=#{ChronuscopClient.configuration_object.api_token}&last_update_at=#{last_update_at}")

      # converting the returned xml page into a hash.
      words_hash = XmlSimple.xml_in(page.body)

      # catching the case when no-translations are returned.
      if(!words_hash) then
        puts "Nothing new added."
        return
      end

      # collecting the translations array.
      all_translations = words_hash["translation"]

      # catching the case when no-translations are returned.
      if(!all_translations) then
        puts "Nothing new added."
        return
      end


      all_translations.each do |t|
        # Inserting into the redis store.
        @redis_agent.set "#{t["key"]}","#{t["value"]}"

        # Bad hack used here. Should fix this.
        str = t["updated-at"][0]["content"]
        key_updated_at = xml_time_to_integer(str)

        # Updating the value last_update_at
        if(key_updated_at > last_update_at) then
          last_update_at = key_updated_at
        end

      end

      # Writing the value of last_update_at to the file.
      write_last_update(last_update_at.to_i)
      puts "Finished synchronizing !!!"
    end
1356611
public function transDocSync($bundle, $key, $locale, $transFile, $document, \DateTime $updatedAt)
    {
        return $this->callService(
            self::SVC_TRANSDOC_SYNC,
            array(
                'bundle'            => $bundle,
                'key'               => $key,
                'locale'            => $locale,
                'file_name'         => $transFile,
                'message'           => $document,
                'last_modification' => $updatedAt->format('c'),
            )
        );
    }
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
929907
public function sync()
    {
        $response = ['success' => true, 'message' => 'Done.'];

        $this->countReviews = 0;
        $this->reviews      = [];
        $this->start        = microtime(true);
        $websites           = $this->helper->getwebsites(true);
        foreach ($websites as $website) {
            $apiEnabled = $this->helper->isEnabled($website);
            $reviewEnabled = $this->helper->getWebsiteConfig(
                \Dotdigitalgroup\Email\Helper\Config::XML_PATH_CONNECTOR_SYNC_REVIEW_ENABLED,
                $website
            );
            $storeIds = $website->getStoreIds();
            if ($apiEnabled && $reviewEnabled && !empty($storeIds)) {
                $this->_exportReviewsForWebsite($website);
            }

            if (isset($this->reviews[$website->getId()])) {
                $reviews = $this->reviews[$website->getId()];
                //send reviews as transactional data
                //register in queue with importer
                $this->importerFactory->create()
                    ->registerQueue(
                        \Dotdigitalgroup\Email\Model\Importer::IMPORT_TYPE_REVIEWS,
                        $reviews,
                        \Dotdigitalgroup\Email\Model\Importer::MODE_BULK,
                        $website->getId()
                    );
                //if no error then set imported
                $this->_setImported($this->reviewIds);
                $this->countReviews += count($reviews);
            }
        }

        if ($this->countReviews) {
            $message = '----------- Review sync ----------- : ' .
                gmdate('H:i:s', microtime(true) - $this->start) .
                ', synced = ' . $this->countReviews;
            $this->helper->log($message);
            $response['message'] = $message;
        }

        return $response;
    }
312135
def tr(self, subdomain: str, string_to_translate: str = "") -> str:
        
        if subdomain not in self.translations.keys():
            raise ValueError(
                "'{}' is not a correct subdomain."
                " Must be one of {}".format(subdomain, self.translations.keys())
            )
        else:
            pass
        # translate
        str_translated = self.translations.get(
            subdomain, {"error": "Subdomain not found: {}".format(subdomain)}
        ).get(string_to_translate, "String not found")

        # end of method
        return str_translated
1159424
private function registerLangPublisher()
    {
        $this->singleton(Contracts\TransPublisher::class, function (Application $app) {
            /**
             * @var  \Illuminate\Filesystem\Filesystem              $files
             * @var  \Arcanedev\LaravelLang\Contracts\TransManager  $manager
             */
            $files   = $app['files'];
            $manager = $app[Contracts\TransManager::class];

            return new TransPublisher($files, $manager, $app->langPath());
        });
    }
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))
45674
def clean_locale(configuration, locale):
    
    dirname = configuration.get_messages_dir(locale)
    if not dirname.exists():
        # Happens when we have a supported locale that doesn't exist in Transifex
        return
    for filename in dirname.files('*.po'):
        clean_file(configuration, dirname.joinpath(filename))
381625
def tr(label, desc = "", tokens = {}, options = {})
      return label if label.tr8n_translated?

      if desc.is_a?(Hash)
        options = desc
        tokens  = options[:tokens] || {}
        desc    = options[:context] || ""
      end

      options.merge!(:caller => caller)
      if request
        options.merge!(:url => request.url)
        options.merge!(:host => request.env['HTTP_HOST'])
      end

      unless Tr8n::Config.enabled?
        return Tr8n::TranslationKey.substitute_tokens(label, tokens, options)
      end

      Tr8n::Config.current_language.translate(label, desc, tokens, options)
    end
473002
private function cacheTranslations() {
        $this->log("Downloading translations...");

        stream_wrapper_register("chdb", '\Tr8n\Cache\Generators\ChdbStream') or die("Failed to register Chdb protocol for streaming Tr8n translation keys");
        $fp = fopen("chdb://ChdbInMemory", "r+");

        $ch = curl_init();
        $url = Config::instance()->application->host . ApiClient::API_PATH . "application/translations?stream=true&client_id=" . Config::instance()->application->key;
        $this->log("GET: " . $url);

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_BUFFERSIZE, 256);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FILE, $fp);

        curl_exec($ch);
        curl_close($ch);
        fclose($fp);
    }
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
        )
1006963
def interlink_translations(content):
    '''
    '''
    lang = content.lang
    # sort translations by lang
    content.translations.sort(key=attrgetter('lang'))
    for translation in content.translations:
        relpath = relpath_to_site(lang, translation.lang)
        url = _NATIVE_CONTENT_URL_DB[translation.source_path]
        translation.override_url = posixpath.join(relpath, url)
288867
public function sync()
    {
        $this->checkStatusForPendingContacts();
        $this->setupAutomationTypes();

        //send the campaign by each types
        foreach ($this->automationTypes as $type => $config) {
            $contacts = $this->buildFirstDimensionOfContactsArray($type, $config);
            //get collection from type
            $automationCollection = $this->automationFactory->create()
                ->getCollectionByType($type, $this->limit);

            foreach ($automationCollection as $automation) {
                $type = $automation->getAutomationType();
                $email = $automation->getEmail();
                $this->typeId = $automation->getTypeId();
                $websiteId = $automation->getWebsiteId();
                $this->storeName = $automation->getStoreName();
                $typeDouble = $type;
                //Set type to generic automation status if type contains constant value
                if (strpos($typeDouble, self::ORDER_STATUS_AUTOMATION) !== false) {
                    $typeDouble = self::ORDER_STATUS_AUTOMATION;
                }
                $contact = $this->helper->getContact($email, $websiteId);
                //contact id is valid, can update datafields
                if ($contact && isset($contact->id)) {
                    if ($contact->status === self::CONTACT_STATUS_PENDING) {
                        $automation->setEnrolmentStatus(self::CONTACT_STATUS_PENDING);
                        $this->automationResource->save($automation);
                        continue;
                    }

                    //need to update datafields
                    $this->updateDatafieldsByType(
                        $typeDouble,
                        $email,
                        $websiteId
                    );
                    $contacts[$automation->getWebsiteId()]['contacts'][$automation->getId()] = $contact->id;
                } else {
                    // the contact is suppressed or the request failed
                    $automation->setEnrolmentStatus('Suppressed');
                    $this->automationResource->save($automation);
                }
            }
            $this->sendAutomationEnrolements($contacts, $type);
        }
    }