TODO: initialize default param as Config.new
 NOTE: temporary code for working construction sharing_tags.switch_context_to
171872
def switch_context_to(name, *attrs)
      Rails.logger.debug "SharingTags: switch context from #{SharingTags.config.current_context.name} to #{name}"
      SharingTags.config.switch_context(name, *attrs)
    end
825442
public void configure(Object obj, Element cfg, int startIdx)
			throws Exception {
		String id = getAttribute(cfg, "id");
		if (id != null) {
			_idMap.put(id, obj);
		}

		Element[] children = getChildren(cfg);

		for (int i = startIdx; i < children.length; i++) {
			Element node = children[i];
			//CHECKSTYLE:OFF
			try {
				// TODO: in case switching to jdk 7, this could be a switch!
				String tag = node.getTagName();
				if ("Set".equals(tag)) {
					set(obj, node);
				} else if ("Put".equals(tag)) {
					put(obj, node);
				} else if ("Call".equals(tag)) {
					call(obj, node);
				} else if ("Get".equals(tag)) {
					get(obj, node);
				} else if ("New".equals(tag)) {
					newObj(obj, node);
				} else if ("Array".equals(tag)) {
					newArray(obj, node);
				} else if ("Ref".equals(tag)) {
					refObj(obj, node);
				} else if ("Property".equals(tag)) {
					propertyObj(obj, node);
				} else {
					throw new IllegalStateException("Unknown tag: " + tag);
				}
			} catch (Exception e) {
				LOG.warn("Config error at " + node, e.toString());
				throw e;
			}
			//CHECKSTYLE:ON
		}
	}
1011583
def _setDefault(self, **kwargs):
        
        for param, value in kwargs.items():
            p = getattr(self, param)
            if value is not None and not isinstance(value, JavaObject):
                try:
                    value = p.typeConverter(value)
                except TypeError as e:
                    raise TypeError('Invalid default param value given for param "%s". %s'
                                    % (p.name, e))
            self._defaultParamMap[p] = value
        return self
1222430
def set_sentry_context(self, tag, value):
        
        if self.sentry_client:
            self.logger.debug('Setting sentry context for %s to %s', tag,
                              value)
            self.sentry_client.tags_context({tag: value})
638339
public void configureWebApp() throws Exception
    {
        //cannot configure if the context is already started
        if (_context.isStarted())
        {
            if (log.isDebugEnabled()){log.debug("Cannot configure webapp after it is started");};
            return;
        }
        
        Resource webInf=getWebApplicationContext().getWebInf();
        // handle any WEB-INF descriptors
        if(webInf!=null&&webInf.isDirectory())
        {
            // do web.xml file
            Resource web=webInf.addPath("web.xml");
            if(!web.exists())
            {
                log.info("No WEB-INF/web.xml in "+getWebApplicationContext().getWAR()
                        +". Serving files and default/dynamic servlets only");
            }
            else
            {
                XmlParser.Node config=null;
                config=xmlParser.parse(web.getURL());
                initialize(config);
            }
        }
    }
951955
def init_with_context(self, context):
        
        from admin_tools.menu.models import Bookmark

        for b in Bookmark.objects.filter(user=context['request'].user):
            self.children.append(MenuItem(mark_safe(b.title), b.url))

        if not len(self.children):
            self.enabled = False
35032
function setDefaultOption(context){var configObj=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var originalData=arguments[2];var rebuild=arguments.length>3&&arguments[3]!==undefined?arguments[3]:false;/**
         * ## setIndexDefault
         *
         * sets a specified index as the default option. This only works
         * correctly if it is a valid index, otherwise it returns null
         *
         * @param {Array} data option data
         * @param {Number} index index
         *
         * @return {Object} default settings
         */function setIndexDefault(data,index){var defaultIndex=index||index===0?index:configObj.defaultIndex;var defaultOption=data[defaultIndex];if(defaultOption){defaultOption.index=defaultIndex;return defaultOption;}return null;}/**
         * ## setPlaceholderDefault
         *
         * sets a placeholder as the default option.  This inserts an empty
         * option first and sets that as default
         *
         * @param {Object} flounder flounder
         *
         * @return {Object} default settings
         */function setPlaceholderDefault(flounder){var refs=flounder.refs;var classes=flounder.classes;var select=refs.select;var placeholder=configObj.placeholder;if(!rebuild||configObj.data){var defaultObj={text:placeholder||placeholder===''?placeholder:defaultOptions.placeholder,value:'',index:0,extraClass:classes.HIDDEN+'  '+classes.PLACEHOLDER};if(select){var escapedText=flounder.allowHTML?defaultObj.text:_utils2.default.escapeHTML(defaultObj.text);var defaultOption=_utils2.default.constructElement({tagname:'option',className:classes.OPTION_TAG,value:defaultObj.value});defaultOption.innerHTML=escapedText;select.insertBefore(defaultOption,select[0]);flounder.refs.selectOptions.unshift(defaultOption);}originalData.unshift(defaultObj);return defaultObj;}return flounder.data[0];}/**
         * ## setValueDefault
         *
         * sets a specified index as the default. This only works correctly if
         * it is a valid value, otherwise it returns null
         *
         * @param {Array} data array of data objects
         * @param {String} val value to set
         *
         * @return {Object} default settings
         */function setValueDefault(data,val){var defaultProp=val||''+configObj.defaultValue;var index=void 0;data.forEach(function(dataObj,i){var dataObjValue=''+dataObj.value;if(dataObjValue===defaultProp){index=i;}});var defaultValue=index>=0?data[index]:null;if(defaultValue){defaultValue.index=index;return defaultValue;}return null;}/**
         * ## checkDefaultPriority
         *
         * sorts out which default should be gotten by priority
         *
         * @return {Object} default data object
         */function checkDefaultPriority(){var data=context.sortData(originalData);if((configObj.multipleTags||configObj.multiple)&&!configObj.defaultIndex&&!configObj.defaultValue){configObj.placeholder=configObj.placeholder||defaultOptions.placeholder;}if(configObj.defaultEmpty){configObj.placeholder='';}var placeholder=configObj.placeholder;if(placeholder||placeholder===''||data.length===0){return setPlaceholderDefault(context,data);}var def=void 0;if(rebuild){var val=context.refs.selected.getAttribute('data-value');def=setValueDefault(data,val);if(def){return def;}}// default prio
def=configObj.defaultIndex?setIndexDefault(data):null;def=!def&&configObj.defaultValue?setValueDefault(data):def;def=!def?setIndexDefault(data,0):def;return def;}originalData=originalData||configObj.data||[];return checkDefaultPriority();}
797801
def init_config(cls):
        
        try:
            # first load current conf and only overwrite needed params
            # we don't want to reset everything
            config_file = os.path.expanduser(cls.home_config)
            config = cls.load(config_file, 'global')
            cls._del('global', 'api.env')

            hidden_apikey = '%s...' % cls.get('api.key', '')[:6]
            apikey = click.prompt('Api key (xmlrpc)',
                                  default=hidden_apikey)
            if apikey == hidden_apikey:
                # if default value then use actual value not hidden one
                apikey = cls.get('api.key')
            env_choice = click.Choice(list(cls.apienvs.keys()))
            apienv = click.prompt('Environnment [production]/ote',
                                  default=cls.default_apienv,
                                  type=env_choice,
                                  show_default=False)
            sshkey = click.prompt('SSH keyfile',
                                  default='~/.ssh/id_rsa.pub')
            hidden_apikeyrest = '%s...' % cls.get('apirest.key', '')[:6]
            apikeyrest = click.prompt('Api key (REST)',
                                      default=hidden_apikeyrest)
            if apikeyrest == hidden_apikeyrest:
                # if default value then use actual value not hidden one
                apikeyrest = cls.get('apirest.key')

            config.update({
                'api': {'key': apikey,
                        'host': cls.apienvs[apienv]},
            })
            if apikeyrest:
                config.update({
                    'apirest': {'key': apikeyrest},
                })

            if sshkey is not None:
                sshkey_file = os.path.expanduser(sshkey)
                if os.path.exists(sshkey_file):
                    config['sshkey'] = [sshkey_file]

            directory = os.path.expanduser(os.path.dirname(config_file))
            if not os.path.exists(directory):
                mkpath(directory, 0o700)

            # save to disk
            cls.save(config_file, config)
            # load in memory
            cls.load(config_file, 'global')
        except (KeyboardInterrupt, click.exceptions.Abort):
            cls.echo('Aborted.')
            sys.exit(1)
654043
public void init(ApplicationConfig config) {
        PropertyMap properties = config.getProperties();
		String contextClassName = properties.getString("contextClass");
        if (contextClassName == null) {
            throw new IllegalArgumentException("contextClass");
        }
        
        try {
            contextClass = Class.forName(contextClassName);
            context = contextClass.newInstance();
            if (context instanceof Context) {
                Context castContext = (Context) context;
                ContextConfig contextConfig = new ContextConfig(
                    config.getProperties(), config.getLog(), 
                    config.getName(), config.getPlugins(),
                    config.getServletContext()
                );
                
                castContext.init(contextConfig);
            }
        } catch (Exception e) {
            throw new RuntimeException(
                "Unable to create context: " + contextClassName, e);
        }
    }
143852
def _init_options(self, kwargs):
        
        self.options = self.task_config.options
        if self.options is None:
            self.options = {}
        if kwargs:
            self.options.update(kwargs)

        # Handle dynamic lookup of project_config values via $project_config.attr
        for option, value in list(self.options.items()):
            try:
                if value.startswith("$project_config."):
                    attr = value.replace("$project_config.", "", 1)
                    self.options[option] = getattr(self.project_config, attr, None)
            except AttributeError:
                pass
775482
@Override
    public void contextInitialized(ServletContextEvent contextEvent) {
        configSupport = new ServletContexConfigSupport();
        if (configSupport.hasHandlers(contextEvent.getServletContext())) {
            AuditManager.startWithConfiguration(configSupport.loadConfig(contextEvent.getServletContext()));
        } else {
            AuditManager.getInstance();
        }
    }
358459
@Override
    public void contextInitialized(ServletContextEvent sce) {
        ServletContext context = sce.getServletContext();
        String propertiesConfig = context.getInitParameter(PROPERTIES_CONFIG);
        if(propertiesConfig == null) {
            propertiesConfig = PROPERTIES_CONFIG_DEFAULT;
        }
        SystemProperties config = loadConfiguration(propertiesConfig, context);
        addProperties(config);
        if(config.getFile() != null) {
            addPropertiesFromFile(config, context);
        }
        
    }
131711
public void initialize(UimaContext context)
			throws ResourceInitializationException {

		super.initialize(context);

		this.context = context;

		mLogger = context.getLogger();

		if (mLogger.isLoggable(Level.INFO)) {
			mLogger.log(Level.INFO, "Initializing the CoGrOO annotator.");
		}

		ComponentFactory factory = ComponentFactory.create(new Locale("pt",
				"BR"));
		cogroo = factory.createPipe();
	}
722109
function defineBuiltinVars(context) {
  // define salesforce package root objects
  for (var key in sf) {
    if (sf.hasOwnProperty(key) && !global[key]) {
      context[key] = sf[key];
    }
  }
  // expose salesforce package root as "$sf" in context.
  context.$sf = sf;

  // create default connection object
  var conn = new sf.Connection();

  for (var prop in conn) {
    if (prop.indexOf('_') === 0) { // ignore private
      continue;
    }
    if (_.isFunction(conn[prop])) {
      context[prop] = _.bind(conn[prop], conn);
    } else if (_.isObject(conn[prop])) {
      defineProp(context, conn, prop);
    }
  }

  // expose default connection as "$conn"
  context.$conn = conn;
}
1139402
def get_context_data(self, parent_context, *tag_args, **tag_kwargs):
        
        target_object = tag_args[0]  # moved one spot due to .pop(0)
        new_context = {
            'STATIC_URL': parent_context.get('STATIC_URL', None),
            'USE_THREADEDCOMMENTS': appsettings.USE_THREADEDCOMMENTS,
            'target_object': target_object,
        }

        # Be configuration independent:
        if new_context['STATIC_URL'] is None:
            try:
                request = parent_context['request']
            except KeyError:
                new_context.update({'STATIC_URL': settings.STATIC_URL})
            else:
                new_context.update(context_processors.static(request))

        return new_context
563439
def set_default_presentation_context(abstract_syntax)
      raise ArgumentError, "Expected String, got #{abstract_syntax.class}" unless abstract_syntax.is_a?(String)
      id = 1
      transfer_syntaxes = [IMPLICIT_LITTLE_ENDIAN, EXPLICIT_LITTLE_ENDIAN, EXPLICIT_BIG_ENDIAN]
      item = {:transfer_syntaxes => transfer_syntaxes}
      pc = {id => item}
      @presentation_contexts = {abstract_syntax => pc}
    end
175690
@Override
    public void contextInitialized(ServletContextEvent evt) {
        File usersDir = new File(SetupOptions.getBaseConfigDirectory(), "users");
        if (!usersDir.isDirectory()) {
            return;
        }
        DocumentBuilder domBuilder = null;
        try {
            domBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            LOGR.warning(e.getMessage());
            return;
        }
        DOMImplementationLS lsFactory = buildDOM3LoadAndSaveFactory();
        LSSerializer serializer = lsFactory.createLSSerializer();
        serializer.getDomConfig().setParameter(Constants.DOM_XMLDECL, Boolean.FALSE);
        serializer.getDomConfig().setParameter(Constants.DOM_FORMAT_PRETTY_PRINT, Boolean.TRUE);
        LSOutput output = lsFactory.createLSOutput();
        output.setEncoding("UTF-8");
        for (File userDir : usersDir.listFiles()) {
            File userFile = new File(userDir, "user.xml");
            if (!userFile.isFile()) {
                continue;
            }
            try {
                Document doc = domBuilder.parse(userFile);
                Node pwNode = doc.getElementsByTagName("password").item(0);
                if (null == pwNode) {
                    continue;
                }
                String password = pwNode.getTextContent();
                if (password.split(":").length == 5) {
                    break;
                }
                pwNode.setTextContent(PasswordStorage.createHash(password));
                // overwrite contents of file
                // Fortify Mod: Make sure that the output stream is closed
                // output.setByteStream(new FileOutputStream(userFile, false));
                FileOutputStream os = new FileOutputStream(userFile, false);
                output.setByteStream(os);
                serializer.write(doc, output);
                os.close();
            } catch (Exception e) {
                LOGR.info(e.getMessage());
                continue;
            }
        }
    }