/*
functions
 
set language to cookie

@function set
@param {Object} my - user option
@param {Object} res - response to client
@param {String} lang - string for cookie
@return {String}
166788
function set(my, res, lang) {

  return res.cookie(my.cookie, lang, {
    domain: my.domain,
    path: my.path,
    maxAge: my.maxAge,
    httpOnly: my.httpOnly,
    secure: my.secure,
    signed: my.signed
  }), lang;
}
491449
function translate(val, scope, status) {
        var app = (scope && scope.appName) || context.get('app') || '';
        var lang = (scope && scope.lang) || context.get('lang') || 'en';
        var translated;

        // if just one character or is a number, don't do translation
        if (!val || val.length < 2 || !isNaN(val)) {
            return val;
        }

        // translations could be either nested (on the server) or at the root (on the client)
        translated = (translations[app] && translations[app][lang] && translations[app][lang][val]) ||
            (_.isString(translations[val]) && translations[val]);

        // if no transation AND caller passed in status object AND lang is not default (i.e. not english),
        // set the status object values which the caller can use to record some info
        // note: this is kind of hacky, but we want the caller (i.e. jng.directives.js) to handle
        // it because jng.directives has more info about the translation than we do at this level
        if (!translated && config.i18nDebug && status && lang !== config.lang.default) {
            status.app = app;
            status.lang = lang;
            status.missing = true;
        }

        // attempt to interpolate and return the resulting value (val if no translation found)
        return interpolate(translated || val, scope);
    }
879231
function loadLocale(lang, callback) {
        // RFC 4646, section 2.1 states that language tags have to be treated as
        // case-insensitive. Convert to lowercase for case-insensitive comparisons.
        if (lang) {
            lang = lang.toLowerCase();
        }

        callback = callback || function _callback() {};

        clear();
        gLanguage = lang;

        // check all <link type="application/l10n" href="..." /> nodes
        // and load the resource files
        var langLinks = getL10nResourceLinks();
        var langCount = langLinks.length;
        if (langCount === 0) {
            // we might have a pre-compiled dictionary instead
            var dict = getL10nDictionary();
            if (dict && dict.locales && dict.default_locale) {
                console.log("using the embedded JSON directory, early way out");
                gL10nData = dict.locales[lang];
                if (!gL10nData) {
                    var defaultLocale = dict.default_locale.toLowerCase();
                    for (var anyCaseLang in dict.locales) {
                        anyCaseLang = anyCaseLang.toLowerCase();
                        if (anyCaseLang === lang) {
                            gL10nData = dict.locales[lang];
                            break;
                        } else if (anyCaseLang === defaultLocale) {
                            gL10nData = dict.locales[defaultLocale];
                        }
                    }
                }
                callback();
            } else {
                console.log("no resource to load, early way out");
            }
            // early way out
            fireL10nReadyEvent(lang);
            gReadyState = "complete";
            return;
        }

        // start the callback when all resources are loaded
        var onResourceLoaded = null;
        var gResourceCount = 0;
        onResourceLoaded = function() {
            gResourceCount++;
            if (gResourceCount >= langCount) {
                callback();
                fireL10nReadyEvent(lang);
                gReadyState = "complete";
            }
        };

        // load all resource files
        function L10nResourceLink(link) {
            var href = link.href;
            // Note: If |gAsyncResourceLoading| is false, then the following callbacks
            // are synchronously called.
            this.load = function(lang, callback) {
                parseResource(href, lang, callback, function() {
                    console.warn(href + " not found.");
                    // lang not found, used default resource instead
                    console.warn('"' + lang + '" resource not found');
                    gLanguage = "";
                    // Resource not loaded, but we still need to call the callback.
                    callback();
                });
            };
        }

        for (var i = 0; i < langCount; i++) {
            var resource = new L10nResourceLink(langLinks[i]);
            resource.load(lang, onResourceLoaded);
        }
    }
908932
def set_language_from
      session[:lang_from] = params[:lang].to_sym
      I18n.locale = session[:lang_from]
      render nothing: true
    end
613770
function createLanguage(parsers) {
  var language = {};
  for (var key in parsers) {
    if ({}.hasOwnProperty.call(parsers, key)) {
      (function(key) {
        var func = function() {
          return parsers[key](language);
        };
        language[key] = lazy(func);
      })(key);
    }
  }
  return language;
}
1082551
function(token, lang, params){

    var scope = this;

    // get language
    lang = utils.getOpenSubtitlesLanguage(lang);

    return utils._getSearchPostData(token, lang, params)
    .then(function(postData){
        return utils.request(API_URL, postData);
    })
    .then(function(response){

        try{
            results = utils.parseXmlSearchResult(response);
        }catch(e){
            results = [];
        }

        //scope.emit.call(scope, "search", results);

        return results;

    });
}
226373
function () {

    // internal purpose only
    if (angular.isFunction(pascalprechtTranslateOverrider.getLocale)) {
      return pascalprechtTranslateOverrider.getLocale();
    }

    var nav = $windowProvider.$get().navigator,
      browserLanguagePropertyKeys = ['language', 'browserLanguage', 'systemLanguage', 'userLanguage'],
      i,
      language;

    // support for HTML 5.1 "navigator.languages"
    if (angular.isArray(nav.languages)) {
      for (i = 0; i < nav.languages.length; i++) {
        language = nav.languages[i];
        if (language && language.length) {
          return language;
        }
      }
    }

    // support for other well known properties in browsers
    for (i = 0; i < browserLanguagePropertyKeys.length; i++) {
      language = nav[browserLanguagePropertyKeys[i]];
      if (language && language.length) {
        return language;
      }
    }

    return null;
  }
1107339
public function setLanguage($language = null)
    {
        if (is_null($language)) {
            if (($language = Yii::$app->request->getQueryParam('_lang')) !== null) {
                $this->language = $language;
                Yii::$app->response->cookies->add(new Cookie(['name' => '_lang', 'value' => $language]));
            } else if (($cookie = Yii::$app->request->cookies->get('_lang')) !== null) {
                $this->language = $cookie->value;
            } else if (($language = Yii::$app->request->getPreferredLanguage()) !== null) {
                $this->language = $language;
            }
        } else {
            $this->language = $language;
        }
    }
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);
}
899607
function setResponseHeaders(res) {
  if(res.setHeader) {
    var contentType = res.getHeader('content-type');
    if (!contentType) {
      res.setHeader('Content-Type', 'application/json');
    }
  }
}
1050850
function () {
    return function (req, res, next) {
      var userModel = models.user;

      if (req.url.indexOf('/api') === 0) {
        req.isApi = true;

        // Make the API requests stateless by removin the cookie set by middleware cookieSession
        onHeaders(res, () => res.removeHeader('Set-Cookie'));

        if (config.api.requireSSL) {
          if (!req.secure && (String(req.headers['x-forwarded-proto']).toLowerCase() !== 'https') ) {
            res.status(403); // forbidden
            res.json({ error: 'All API requests must be made over SSL/TLS' });
            return;
          }
        }

        if (req.query.api_key) {
          req.apiKey = req.query.api_key;
        } else if (req.headers.authorization) {
          req.apiKey = req.headers.authorization.replace(/token\s/i,'');
        }

        var validateApiRequest = function () {
          if (config.api.allowAnonymousReadWrite || (config.api.allowAnonymousRead && req.method === 'GET')) {
            next();
          } else {
            if (!req.apiKey) {
              res.status(403); // forbidden
              res.json({ error: 'You need to provide a valid API key when using this API' });
            } else {
              next();
            }
          }
        };

        if (req.apiKey) {
          userModel.loadByApiKey(req.apiKey, function (err, user) {
            if (err) {
              return next(err);
            }
            if (user) {
              req.session.user = user;

              // since we're setting the user session via the API
              // we need to ensure that the user is totally trashed
              // from the session to avoid abuse directly in the browser
              // i.e. stolen api key can only create bins, nothing more.
              onHeaders(res, () => delete req.session);

              validateApiRequest();
            } else {
              res.status(403); // forbidden
              res.json({ error: 'The API key you provided is not valid' });
            }
          });
        } else {
          validateApiRequest();
        }
      } else {
        next();
      }
    };
  }
39279
private Cookie generateLanguageCookie(String language) {
        Cookie cookie = new Cookie(applicationCookiePrefix + "_LANG", language);
        cookie.setSecure(true);
        cookie.setMaxAge(TEN_YEARS);
        return cookie;
    }
929597
function (locale, callback) {

            var self = this;

            if (!locale) {
                callback && callback("locale not defined");
                return;
            }

            require(['json!' + self.$.path + '/' + self.$.locale], function (translations) {
                self.set({
                    translations: translations
                });
                callback && callback();
            }, function (err) {
                self.log(err, 'error');
                callback && callback(err);
            });

        }
521255
function (langs, success, error) {
		if (typeof langs === 'string') {
			langs = [langs];
		}
		var i = 0;
		var l = langs.length;
		var f = function () {
			if (i < l) {
				loadLanguage(langs[i], function () {
					i++;
					f();
				}, function () {
					error && error(langs[i]);
				});
			} else if (i === l) {
				success && success(langs);
			}
		};
		f();
	}
655831
function setResCookies(ctx, headers) {
    if (!headers || !validateCookies(headers['set-cookie'])) {
      return
    }

    let cookies = headers['set-cookie'];
    let _headers = ctx.res._headers || {};
    ctx.res._headerNames = ctx.res._headerNames || {}
    // 参考：https://github.com/nodejs/node/blob/master/lib/_http_outgoing.js
    // 在Nodejs 8.x的版本里res._headers被改成了getter/setter 通过 headers['set-cookies'] = 'test' 不触发setter，从而导致设置cookie报错
    ctx.res._headers = Object.assign({}, _headers, {
      'set-cookie': (_headers['set-cookie'] || []).concat(cookies)
    })
    ctx.res._headerNames['set-cookie'] = 'Set-Cookie';
  }
936655
function resolveLanguage ( value ) {
	if ( typeof value === 'string' ) {
		const lang = _.find(langs, ( o ) => { return o.locale.indexOf(value) !== -1; });
		if ( typeof lang !== 'undefined' ) {
			return lang.id;
		}
	}
	return value;
}
451136
function setLanguage(req) {
        var host = req.info.host;

        // hack fix for m.reviews, m.fr, m.es, etc.
        if (host.substring(0, 2) === 'm.') {
            req.app.isLegacyMobile = true;
            host = host.substring(2);
        }

        var subdomain = host.substring(0, 2);

        // either at language-based subdomain or we use english
        req.app.lang = (host.charAt(2) === '.' && langSubdomains.indexOf(subdomain) >= 0) ?
            subdomain : 'en';
    }