text:
define([
    'underscore',
    'moment',
    'query-form-view',
    'knockback',
    "core-constants",
    'core-basedir/js/models/NodeConsoleLogsModel',
    'core-basedir/reports/qe/ui/js/common/qe.utils'
], function (_, moment, QueryFormView, Knockback, coreConstants, NodeConsoleLogsModel, qeUtils) {
    var nodeType,hostname;
    var NodeConsoleLogsView = QueryFormView.extend({
        render: function () {
            var self = this,
                viewConfig = self.attributes.viewConfig,
                modelMap = contrail.handleIfNull(self.modelMap, {}),
                elementId = self.attributes.elementId,
                queryPageTmpl = contrail.getTemplate4Id(coreConstants.TMPL_QUERY_PAGE),
                consoleLogsModel = new NodeConsoleLogsModel(),
                queryFormId = coreConstants.QE_HASH_ELEMENT_PREFIX + coreConstants.CONSOLE_LOGS_PREFIX + coreConstants.QE_FORM_SUFFIX;

            hostname = viewConfig.hostname;
            nodeType = viewConfig.nodeType;
            consoleLogsModel.node_type(nodeType);
            consoleLogsModel.hostname(hostname);
            self.model = consoleLogsModel;

            self.$el.append(queryPageTmpl({queryPrefix: coreConstants.CONSOLE_LOGS_PREFIX }));

            self.renderView4Config($(self.$el).find(queryFormId), this.model, self.getViewConfig(), null, null, modelMap, function () {
                self.model.showErrorAttr(elementId, false);
                Knockback.applyBindings(self.model, document.getElementById(elementId));
                kbValidation.bind(self);
                $("#display_logs").on('click', function() {
                    self.renderQueryResult();
                });
                self.getLastLogTimeStampAndRenderResults(self,consoleLogsModel);

            });
        },

        getLastLogTimeStampAndRenderResults : function(self,consoleLogsModel) {
            var postData = monitorInfraUtils.getPostDataForGeneratorType(
                                {
                                    nodeType:nodeType,
                                    cfilt:"ModuleServerState:msg_stats",
                                    hostname:hostname
                                }
                            );
            $.ajax({
                url:coreConstants.TENANT_API_URL,
                type:'post',
                data:postData,
                dataType:'json'
            }).done(function (result) {
                //Update the logtype combobox which is dependent on the same results.
                self.updateLogTypeDropdown(result);
                var logLevelStats = [], lastLog, lastMsgLogTime, lastTimeStamp,
                    allStats = [],defaultTimeRange = 600;
                try{
                    allStats =  ifNullOrEmptyObject(jsonPath(result,"$..log_level_stats"),[]);
                }catch(e){}
                if(allStats instanceof Array){
                    for(var i = 0; i < allStats.length;i++){
                        if(!($.isEmptyObject(allStats[i]))){
                            if( allStats[i] instanceof Array){
                                logLevelStats = logLevelStats.concat(allStats[i]);
                            } else {
                                logLevelStats.push(allStats[i]);
                            }
                        }
                    }
                }
                if(logLevelStats != null){
                    lastLog = monitorInfraUtils.getMaxGeneratorValueInArray(logLevelStats,"last_msg_timestamp");
                    if(lastLog != null){
                        lastTimeStamp = parseInt(lastLog.last_msg_timestamp)/1000 + 1000;
                        lastLogLevel = lastLog.level;
                    }
                }
                if(lastTimeStamp == null || lastMsgLogTime != lastTimeStamp){
                    lastMsgLogTime = lastTimeStamp;
                    if(lastMsgLogTime != null && lastLogLevel != null){
                        consoleLogsModel.to_time(new Date(lastMsgLogTime));
                        consoleLogsModel.from_time(moment(new Date(lastMsgLogTime)).subtract('s', defaultTimeRange));
                        consoleLogsModel.log_level(self.getLogLevelValueFromLogLevel(lastLogLevel));
                        consoleLogsModel.time_range('-1');
                    }
                    self.renderQueryResult();
                }
            });

        },

        updateLogTypeDropdown : function(result) {

            var msgTypeStatsList = [{text:'Any',value:'any'}];
            var msgStats = [];
            try{
                msgStats =  ifNullOrEmptyObject(jsonPath(result,"$..msgtype_stats"),[]);
            }catch(e){}
            if(msgStats instanceof Array){
                for(var i = 0; i < msgStats.length;i++){
                    if(!($.isEmptyObject(msgStats[i]))){
                        if( msgStats[i] instanceof Array){
                            $.each(msgStats[i],function(i,msgStat){
                                var msgType = msgStat['message_type'];
                                msgTypeStatsList.push({text:msgType,value:msgType});
                            });
                        } else {
                            msgTypeStatsList.push({text:msgStats[i]['message_type'],value:msgStats[i]['message_type']});
                        }
                    }
                }
            }
            var logTypeDd = $('#log_type_dropdown').data('contrailDropdown');
            if(logTypeDd != null) {
                logTypeDd.setData(msgTypeStatsList);
                logTypeDd.value('any');
            }
        },

        getLogLevelValueFromLogLevel : function (logLevel) {
            var qeLevels = coreConstants.QE_LOG_LEVELS;
            $.each(qeLevels, function(key,levelObj) {
                if(levelObj.name == logLevel) {
                    return levelObj.value;
                }
            })
        },

        renderQueryResult: function() {
            var self = this,
                modelMap = contrail.handleIfNull(self.modelMap, {}),
                queryFormModel = self.model,
                queryResultId = coreConstants.QE_HASH_ELEMENT_PREFIX + coreConstants.CONSOLE_LOGS_PREFIX + coreConstants.QE_RESULTS_SUFFIX,
                queryResultTabId = cowl.QE_SYSTEM_LOGS_TAB_ID;

            formatQueryParams(queryFormModel);

            queryFormModel.is_request_in_progress(true);
            qeUtils.fetchServerCurrentTime(function(serverCurrentTime) {
                var timeRange = parseInt(queryFormModel.time_range()),
                    queryRequestPostData;

                if (timeRange !== -1) {
                    queryFormModel.to_time(serverCurrentTime);
                    queryFormModel.from_time(serverCurrentTime - (timeRange * 1000));
                }

                queryRequestPostData = queryFormModel.getQueryRequestPostData(serverCurrentTime);
                queryRequestPostData.chunkSize = coreConstants.QE_RESULT_CHUNK_SIZE_10K;
                self.renderView4Config($(queryResultId), queryFormModel,
                    getQueryResultTabViewConfig(queryRequestPostData, queryResultTabId), null, null, modelMap,
                    function() {
                        var queryResultListModel = modelMap[coreConstants.UMID_QUERY_RESULT_LIST_MODEL];

                        queryResultListModel.onAllRequestsComplete.subscribe(function () {
                            queryFormModel.is_request_in_progress(false);
                        });
                    });
            });
        },

        getViewConfig: function () {
            var self = this;
            return {
                view: "SectionView",
                viewConfig: {
                    rows: [
                        {
                            columns: [
                                {
                                    elementId: 'keywords', view: "FormInputView",
                                    viewConfig: { path: 'keywords', dataBindValue: 'keywords', class: "col-xs-6", placeholder: "Enter keyword(s)"}
                                }
                            ]
                        },
                        {
                            viewConfig: {
                                visible: 'show_advanced_options()'
                            },
                            columns: [
                                {
                                    elementId: 'time_range', view: "FormDropdownView",
                                    viewConfig: {
                                        path: 'time_range', dataBindValue: 'time_range', class: "col-xs-2",
                                        elementConfig: {dataTextField: "text", dataValueField: "id", data: coreConstants.TIMERANGE_DROPDOWN_VALUES}}
                                },
                                {
                                    elementId: 'from_time', view: "FormDateTimePickerView",
                                    viewConfig: {
                                        style: 'display: none;',
                                        path: 'from_time', dataBindValue: 'from_time', class: "col-xs-4",
                                        elementConfig: qeUtils.getFromTimeElementConfig('from_time', 'to_time'),
                                        visible: "isTimeRangeCustom()"
                                    }
                                },
                                {
                                    elementId: 'to_time', view: "FormDateTimePickerView",
                                    viewConfig: {
                                        style: 'display: none;',
                                        path: 'to_time', dataBindValue: 'to_time', class: "col-xs-4",
                                        elementConfig: qeUtils.getToTimeElementConfig('from_time', 'to_time'),
                                        visible: "isTimeRangeCustom()"
                                    }
                                }
                            ]
                        },
                        {
                            viewConfig: {
                                visible: 'show_advanced_options()'
                            },
                            columns: [
                                {
                                    elementId: 'log_category', view: "FormDropdownView",
                                    viewConfig: {
                                        path: 'log_category', dataBindValue: 'log_category', class: "col-xs-2",
                                        elementConfig: {
                                            dataTextField: "text",
                                            dataValueField: "value",
                                            defaultValueId: 0,
                                            dataSource: {
                                                type:'remote',
                                                url: monitorInfraConstants.
                                                        monitorInfraUrls
                                                            ['MSGTABLE_CATEGORY'],
                                                async:true,
                                                parse:function(response){
                                                    var ret = [{text:'All',value:'All'}];
                                                    var catList = [];
                                                    if (nodeType == monitorInfraConstants.CONTROL_NODE){
                                                        catList = ifNull(response[coreConstants.UVEModuleIds['CONTROLNODE']], []);
                                                    } else if (nodeType == monitorInfraConstants.COMPUTE_NODE) {
                                                        catList = ifNull(response[coreConstants.UVEModuleIds['VROUTER_AGENT']], []);
                                                    } else if (nodeType == monitorInfraConstants.ANALYTICS_NODE) {
                                                        catList = ifNull(response[coreConstants.UVEModuleIds['COLLECTOR']], []);
                                                    } else if (nodeType == monitorInfraConstants.CONFIG_NODE) {
                                                        catList = ifNull(response[coreConstants.UVEModuleIds['APISERVER']], []);
                                                    }
                                                    $.each(catList, function (key, value) {
                                                        if(key != '')
                                                            ret.push({text:value, value:value});
                                                    });
                                                    return ret;
                                                }
                                            }
                                        }
                                    }
                                },
                                {
                                    elementId: 'log_type', view: "FormDropdownView",
                                    viewConfig: {
                                        path: 'log_type', dataBindValue: 'log_type', class: "col-xs-2",
                                        elementConfig: {
                                            dataTextField: "text",
                                            dataValueField: "value",
                                            defaultValueId: 0,
                                            dataSource: {
                                                data:[{text:'Any',value:'any'}]
                                            }
                                        }
                                    }
                                },
                                {
                                    elementId: 'log_level', view: "FormDropdownView",
                                    viewConfig: { path: 'log_level', dataBindValue: 'log_level', class: "col-xs-2", elementConfig: {dataTextField: "name", dataValueField: "value", data: coreConstants.QE_LOG_LEVELS}}
                                },
                                {
                                    elementId: 'limit', view: "FormDropdownView",
                                    viewConfig: { path: 'limit', dataBindValue: 'limit', class: "col-xs-2", elementConfig: {dataTextField: "text", dataValueField: "id", data:coreConstants.CONSOLE_LOGS_LIMITS}}
                                }
                            ]
                        },
                        {
                            columns: [
                                {
                                    elementId: 'advanced_options', view: "FormTextView",
                                    viewConfig: {
                                        text: 'getAdvancedOptionsText()',
                                        class: "col-xs-6 margin-0-0-10",
                                        elementConfig : {
                                            class: "advanced-options-link"
                                        },
                                        click: 'toggleAdvancedFields'
                                    }
                                }
                            ]
                        },
                        {
                            columns: [
                                {
                                    elementId: 'display_logs', view: "FormButtonView", label: "Display Logs",
                                    viewConfig: {
                                        class: 'display-inline-block margin-0-0-0-15',
                                        disabled: 'is_request_in_progress()',
                                        elementConfig: {
                                            btnClass: 'btn-primary'
                                        }
                                    }
                                },
                                {
                                    elementId: 'reset_query', view: "FormButtonView", label: "Reset",
                                    viewConfig: {
                                        label: "Reset",
                                        class: 'display-inline-block margin-0-0-0-15',
                                        elementConfig: {
                                            onClick: "reset"
                                        }
                                    }
                                }
                            ]
                        }
                    ]
                }
            };
        }
    });

    function formatQueryParams(model) {
        var limit = model.limit();
        var keywords = model.keywords();
        var filters = "limit:" + limit;
        var msgType = model.log_type();
        var hostname = model.hostname();
        var nodeType = model.node_type();
        if(msgType == 'any'){
            msgType = '';
        }
        if(keywords != '') {
            filters += ",keywords:" + keywords;
        }
        if(nodeType == monitorInfraConstants.CONTROL_NODE) {
            if(msgType != ''){
                model.where ('(ModuleId=' + coreConstants.UVEModuleIds['CONTROLNODE']
                    + ' AND Source='+ hostname +' AND Messagetype='+ msgType +')');
            } else {
                model.where( '(ModuleId=' + coreConstants.UVEModuleIds['CONTROLNODE']
                    + ' AND Source='+ hostname +')' );
            }
        } else if (nodeType == monitorInfraConstants.COMPUTE_NODE) {
            var moduleId = coreConstants.UVEModuleIds['VROUTER_AGENT'];
            var msgType = model.log_type();
            var hostname = model.hostname();
            //TODO check if the below is needed
//            if(obj['vrouterModuleId'] != null && obj['vrouterModuleId'] != ''){
//                moduleId = obj['vrouterModuleId'];
//            }
            if(msgType != ''){
                model.where('(ModuleId=' + moduleId + ' AND Source='+ hostname
                        +' AND Messagetype='+ msgType +')' );
            } else {
                model.where( '(ModuleId=' + moduleId + ' AND Source='+ hostname +')' );
            }
        } else if (nodeType == monitorInfraConstants.CONFIG_NODE) {
            if(msgType != ''){
                model.where( '(ModuleId=' + coreConstants.UVEModuleIds['SCHEMA']
                    + ' AND Source='+hostname+' AND Messagetype='+ msgType
                    +') OR (ModuleId=' + coreConstants.UVEModuleIds['APISERVER']
                    + ' AND Source='+hostname+' AND Messagetype='+ msgType
                    +') OR (ModuleId=' + coreConstants.UVEModuleIds['SERVICE_MONITOR']
                    + ' AND Source='+hostname+' AND Messagetype='+ msgType
                    +') OR (ModuleId=' + coreConstants.UVEModuleIds['DISCOVERY_SERVICE']
                    + ' AND Source='+hostname+' AND Messagetype='+ msgType +')');
            } else {
                model.where( '(ModuleId=' + coreConstants.UVEModuleIds['SCHEMA']
                    + ' AND Source='+hostname+') OR (ModuleId='
                    + coreConstants.UVEModuleIds['APISERVER']
                    + ' AND Source='+hostname+') OR (ModuleId='
                    + coreConstants.UVEModuleIds['SERVICE_MONITOR']
                    + ' AND Source='+hostname+') OR (ModuleId='
                    + coreConstants.UVEModuleIds['DISCOVERY_SERVICE']
                    + ' AND Source='+hostname+')' );
            }
        } else if (nodeType == monitorInfraConstants.ANALYTICS_NODE) {
            if(msgType != ''){
                model.where( '(ModuleId=' + coreConstants.UVEModuleIds['OPSERVER']
                    + ' AND Source='+hostname+' AND Messagetype='+ msgType
                    +') OR (ModuleId=' + coreConstants.UVEModuleIds['COLLECTOR']
                    + ' AND Source='+hostname+' AND Messagetype='+ msgType +')' );
            } else {
                model.where( '(ModuleId=' + coreConstants.UVEModuleIds['OPSERVER']
                    + ' AND Source='+hostname+') OR (ModuleId='
                    + coreConstants.UVEModuleIds['COLLECTOR']
                    + ' AND Source='+hostname+')');
            }
        }
        model.filters(filters);

        //TODO: Add where clause for category, type, and keywords. Add where clause corresponding to node type.
    };

    function getQueryResultTabViewConfig(queryRequestPostData, queryResultTabId) {
        return {
            elementId: queryResultTabId,
            view: "TabsView",
            viewConfig: {
                theme: coreConstants.TAB_THEME_WIDGET_CLASSIC,
                tabs: [getQueryResultGridViewConfig(queryRequestPostData)]
            }
        };
    }

    function getQueryResultGridViewConfig(queryRequestPostData) {
        return {
            elementId: cowl.QE_QUERY_RESULT_GRID_ID,
            title: cowl.TITLE_RESULTS,
            iconClass: 'fa fa-table',
            view: 'QueryResultGridView',
            tabConfig: {
                //TODO
            },
            viewConfig: {
                queryRequestPostData: queryRequestPostData,
                gridOptions: {
                    titleText: cowl.TITLE_SYSTEM_LOGS,
                    queryQueueUrl: coreConstants.URL_QUERY_LOG_QUEUE,
                    queryQueueTitle: cowl.TITLE_LOG
                }
            }
        }
    }

    return NodeConsoleLogsView;
});


text:
namespace System.Windows.Forms {

    using System.Diagnostics;

    using System;
    using System.Drawing;

    /// <include file='doc\GiveFeedbackEventHandler.uex' path='docs/doc[@for="GiveFeedbackEventHandler"]/*' />
    /// <devdoc>
    ///    <para>
    ///       Represents the method that handles the <see cref='System.Windows.Forms.Control.GiveFeedback'/> event
    ///       of a <see cref='System.Windows.Forms.Control'/>.
    ///    </para>
    /// </devdoc>
    public delegate void GiveFeedbackEventHandler(object sender, GiveFeedbackEventArgs e);
}

redpajama_set_name: RedPajamaGithub


text:
This folder contains the script to be executed.
The main script weatherdata.py is an infinite loop that sleeps N seconds between reads.
runweather.sh is launcher script for running at startup


text:
package org.apache.velocity.runtime.parser.node;

import org.apache.velocity.context.InternalContextAdapter;
import org.apache.velocity.exception.TemplateInitException;
import org.apache.velocity.runtime.parser.Parser;

public class ASTDirectiveAssign extends SimpleNode
{

  public ASTDirectiveAssign(int i)
  {
    super(i);
  }

  public ASTDirectiveAssign(Parser p, int i)
  {
    super(p, i);
  }

  /**
   * @throws TemplateInitException
   * @see org.apache.velocity.runtime.parser.node.Node#init(org.apache.velocity.context.InternalContextAdapter, java.lang.Object)
   */
  @Override
  public Object init(InternalContextAdapter context, Object data) throws TemplateInitException
  {
  	Object obj = super.init(context, data);
  	saveTokenImages();
  	cleanupParserAndTokens(); // drop reference to Parser and all JavaCC Tokens
  	return obj;
  }

}


text:
#include <aws/ec2/model/GetInstanceUefiDataResponse.h>
#include <aws/core/utils/xml/XmlSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/logging/LogMacros.h>

#include <utility>

using namespace Aws::EC2::Model;
using namespace Aws::Utils::Xml;
using namespace Aws::Utils::Logging;
using namespace Aws::Utils;
using namespace Aws;

GetInstanceUefiDataResponse::GetInstanceUefiDataResponse()
{
}

GetInstanceUefiDataResponse::GetInstanceUefiDataResponse(const Aws::AmazonWebServiceResult<XmlDocument>& result)
{
  *this = result;
}

GetInstanceUefiDataResponse& GetInstanceUefiDataResponse::operator =(const Aws::AmazonWebServiceResult<XmlDocument>& result)
{
  const XmlDocument& xmlDocument = result.GetPayload();
  XmlNode rootNode = xmlDocument.GetRootElement();
  XmlNode resultNode = rootNode;
  if (!rootNode.IsNull() && (rootNode.GetName() != "GetInstanceUefiDataResponse"))
  {
    resultNode = rootNode.FirstChild("GetInstanceUefiDataResponse");
  }

  if(!resultNode.IsNull())
  {
    XmlNode instanceIdNode = resultNode.FirstChild("instanceId");
    if(!instanceIdNode.IsNull())
    {
      m_instanceId = Aws::Utils::Xml::DecodeEscapedXmlText(instanceIdNode.GetText());
    }
    XmlNode uefiDataNode = resultNode.FirstChild("uefiData");
    if(!uefiDataNode.IsNull())
    {
      m_uefiData = Aws::Utils::Xml::DecodeEscapedXmlText(uefiDataNode.GetText());
    }
  }

  if (!rootNode.IsNull()) {
    XmlNode requestIdNode = rootNode.FirstChild("requestId");
    if (!requestIdNode.IsNull())
    {
      m_responseMetadata.SetRequestId(StringUtils::Trim(requestIdNode.GetText().c_str()));
    }
    AWS_LOGSTREAM_DEBUG("Aws::EC2::Model::GetInstanceUefiDataResponse", "x-amzn-request-id: " << m_responseMetadata.GetRequestId() );
  }
  return *this;
}


text:
"""Training state management."""

import os

import tensorflow.compat.v2 as tf

from keras import backend
from keras.distribute import distributed_file_utils
from keras.utils import mode_keys

# isort: off
from keras.distribute.distributed_file_utils import (
    support_on_demand_checkpoint_callback,
)  # noqa: E501

MAX_CHECKPOINT_TO_KEEP = 1

def _should_enable_save_before_preemption(save_before_preemption_arg, strategy):
    # TODO(wxinyi): expand support to TPU.
    return (
        save_before_preemption_arg
        and isinstance(strategy, tf.distribute.MultiWorkerMirroredStrategy)
        and support_on_demand_checkpoint_callback()
    )

class WorkerTrainingState:
    """Training state management class.

    This class provides apis for backing up and restoring the training state.
    This allows model and epoch and batch information to be saved periodically
    and restore for fault-tolerance, also known as preemption-recovery purpose.
    """

    # Constant for `tf.keras.Model` attribute to store the epoch and batch
    # at which the most recently saved checkpoint was saved.
    CKPT_SAVED_EPOCH_UNUSED_VALUE = -1

    CKPT_SAVED_BATCH_UNUSED_VALUE = -1

    def __init__(
        self,
        model,
        checkpoint_dir,
        save_freq="epoch",
        save_before_preemption_arg=None,
    ):
        self._enable_save_before_preemption = (
            _should_enable_save_before_preemption(
                save_before_preemption_arg, model.distribute_strategy
            )
        )
        self._model = model
        self._save_freq = save_freq
        # The batch and epoch at which the checkpoint is saved. Used for
        # fault-tolerance. GPU device only has int64 dtype registered
        # VarHandleOp.
        self._ckpt_saved_epoch = tf.Variable(
            initial_value=tf.constant(
                self.CKPT_SAVED_EPOCH_UNUSED_VALUE, dtype=tf.int64
            ),
            name="ckpt_saved_epoch",
        )
        self._ckpt_saved_batch = tf.Variable(
            initial_value=tf.constant(
                self.CKPT_SAVED_BATCH_UNUSED_VALUE, dtype=tf.int64
            ),
            name="ckpt_saved_batch",
        )
        # Variable initialization.
        backend.set_value(
            self._ckpt_saved_epoch, self.CKPT_SAVED_EPOCH_UNUSED_VALUE
        )
        backend.set_value(
            self._ckpt_saved_batch, self.CKPT_SAVED_BATCH_UNUSED_VALUE
        )
        # _ckpt_saved_epoch and _ckpt_saved_batch gets tracked and is included
        # in the checkpoint file when backing up.
        checkpoint = tf.train.Checkpoint(
            model=self._model,
            ckpt_saved_epoch=self._ckpt_saved_epoch,
            ckpt_saved_batch=self._ckpt_saved_batch,
            train_counter=self._model._train_counter,
        )

        # If this is single-worker training, checkpoint_dir are the same for
        # write_checkpoint_manager and read_checkpoint_manager.
        #
        # If this is multi-worker training, and this worker should not save
        # checkpoint, we replace the write_checkpoint_manager's checkpoint_dir
        # with a temp filepath, so it writes to a file that will be removed at
        # the end of back_up() call. This is necessary because the
        # SyncOnReadVariable needs to be synced across all the workers in order
        # to be read, and all workers need to perform `save()`.  But all workers
        # should restore from the same checkpoint_dir as passed in
        # read_checkpoint_manager.
        self.read_checkpoint_manager = tf.train.CheckpointManager(
            checkpoint,
            directory=os.path.join(checkpoint_dir, "chief"),
            max_to_keep=MAX_CHECKPOINT_TO_KEEP,
        )
        write_checkpoint_dir = distributed_file_utils.write_dirpath(
            checkpoint_dir, self._model.distribute_strategy
        )
        if self._model.distribute_strategy.extended.should_checkpoint:
            self.write_checkpoint_manager = self.read_checkpoint_manager
        else:
            self.write_checkpoint_manager = tf.train.CheckpointManager(
                checkpoint,
                directory=write_checkpoint_dir,
                max_to_keep=MAX_CHECKPOINT_TO_KEEP,
            )

        if self._enable_save_before_preemption:
            self.preemption_handler = (
                tf.distribute.experimental.PreemptionCheckpointHandler(
                    self._model.distribute_strategy.extended._cluster_resolver,
                    self.write_checkpoint_manager,
                )
            )
            self.preemption_handler._read_checkpoint_manager = (
                self.read_checkpoint_manager
            )

    def back_up(self, epoch, batch=0):
        """Back up the current state of training into a checkpoint file.

        Args:
          epoch: The current epoch information to be saved.
          batch: The current batch(step) information to be saved.
        """
        # Save the model plus CKPT_SAVED_EPOCH and CKPT_SAVED_BATCH variable.
        if self.write_checkpoint_manager.save():
            distributed_file_utils.remove_temp_dirpath(
                self.write_checkpoint_manager.directory,
                self._model.distribute_strategy,
            )

    def backup_if_preempted(self):
        if self._enable_save_before_preemption:
            self.preemption_handler._run_counter += 1
            self.preemption_handler._checkpoint_if_preempted()

    def restore(self):
        """Restore the training state from the backed up checkpoint file.

        Returns:
          True if the training state is successfully restored. False if the
          training state doesn't need to be restored, or error occurred so it
          can't.
        """
        # When creating the PreemptionCheckpointHandler object, we have already
        # restored the checkpoint.
        if not self._enable_save_before_preemption:
            self.read_checkpoint_manager.restore_or_initialize()

    def delete_backup(self):
        """Delete the backup directories.

        Delete the backup directories which should not exist after `fit()`
        successfully finishes.
        """
        if self.write_checkpoint_manager is self.read_checkpoint_manager:
            try:
                tf.io.gfile.rmtree(self.write_checkpoint_manager.directory)
            except tf.errors.NotFoundError:
                pass

    def maybe_load_initial_counters_from_ckpt(
        self, steps_per_epoch, initial_epoch, mode
    ):
        """Maybe load 1st epoch from checkpoint, considering worker recovery.

        When `_ckpt_saved_epoch` attribute exists and is not
        `CKPT_SAVED_EPOCH_UNUSED_VALUE`, this is under multi-worker training
        setting and indicates the worker is recovering from previous failure. In
        this case, infer `initial_epoch` from `self._ckpt_saved_epoch` to
        continue previous unfinished training from certain epoch.

        Args:
          steps_per_epoch: The number of steps per epoch value.
          initial_epoch: The original initial_epoch user passes in in `fit()`.
          mode: The mode for running `model.fit()`.

        Returns:
          If the training is recovering from previous failure under multi-worker
          training setting, return the (epoch, step) the training is supposed to
          continue at. Otherwise, return the `initial_epoch, initial_step` the
          user passes in.
        """

        initial_step = 0
        epoch = backend.eval(self._ckpt_saved_epoch)
        batch = backend.eval(self._ckpt_saved_batch)
        if mode == mode_keys.ModeKeys.TRAIN:
            # For batch-level saving
            if self._enable_save_before_preemption or isinstance(
                self._save_freq, int
            ):
                if batch >= 0:
                    # If the checkpoint was last saved at last batch of the
                    # epoch, return the next epoch number and batch=0
                    if batch == steps_per_epoch - 1:
                        initial_epoch = epoch + 1
                        initial_step = 0
                    else:
                        # If the checkpoint was not last saved at last batch of
                        # the epoch, return the same epoch and next batch number
                        initial_epoch = epoch
                        initial_step = batch + 1
            else:
                if epoch >= 0:
                    # The most recently saved epoch is one epoch prior to the
                    # epoch it failed at, so return the value of
                    # 'self._ckpt_saved_epoch' plus one.
                    initial_epoch = epoch + 1

        return (initial_epoch, initial_step)


text:
using std::string;
using std::vector;

namespace tcframe {

struct SubtaskYaml {
    double points;
};

struct EvaluatorYaml {
    string slug;
    bool has_tc_output;
    bool has_scorer;
};

struct LimitsYaml {
    int time_s;
    int memory_mb;
};

struct SpecYaml {
    string slug;
    vector<SubtaskYaml> subtasks;
    EvaluatorYaml evaluator;
    LimitsYaml limits;
};

}


text:
package jwtmiddleware

// Option is how options for the JWTMiddleware are set up.
type Option func(*JWTMiddleware)

// WithCredentialsOptional sets up if credentials are
// optional or not. If set to true then an empty token
// will be considered valid.
//
// Default value: false.
func WithCredentialsOptional(value bool) Option {
	return func(m *JWTMiddleware) {
		m.credentialsOptional = value
	}
}

// WithValidateOnOptions sets up if OPTIONS requests
// should have their JWT validated or not.
//
// Default value: true.
func WithValidateOnOptions(value bool) Option {
	return func(m *JWTMiddleware) {
		m.validateOnOptions = value
	}
}

// WithErrorHandler sets the handler which is called
// when we encounter errors in the JWTMiddleware.
// See the ErrorHandler type for more information.
//
// Default value: DefaultErrorHandler.
func WithErrorHandler(h ErrorHandler) Option {
	return func(m *JWTMiddleware) {
		m.errorHandler = h
	}
}

// WithTokenExtractor sets up the function which extracts
// the JWT to be validated from the request.
//
// Default value: AuthHeaderTokenExtractor.
func WithTokenExtractor(e TokenExtractor) Option {
	return func(m *JWTMiddleware) {
		m.tokenExtractor = e
	}
}


text:
package com.google.ads.googleads.v10.resources;

import com.google.api.pathtemplate.PathTemplate;
import com.google.api.resourcenames.ResourceName;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import javax.annotation.Generated;

// AUTO-GENERATED DOCUMENTATION AND CLASS.
@Generated("by gapic-generator-java")
public class GeoTargetConstantName implements ResourceName {
  private static final PathTemplate CRITERION_ID =
      PathTemplate.createWithoutUrlEncoding("geoTargetConstants/{criterion_id}");
  private volatile Map<String, String> fieldValuesMap;
  private final String criterionId;

  @Deprecated
  protected GeoTargetConstantName() {
    criterionId = null;
  }

  private GeoTargetConstantName(Builder builder) {
    criterionId = Preconditions.checkNotNull(builder.getCriterionId());
  }

  public String getCriterionId() {
    return criterionId;
  }

  public static Builder newBuilder() {
    return new Builder();
  }

  public Builder toBuilder() {
    return new Builder(this);
  }

  public static GeoTargetConstantName of(String criterionId) {
    return newBuilder().setCriterionId(criterionId).build();
  }

  public static String format(String criterionId) {
    return newBuilder().setCriterionId(criterionId).build().toString();
  }

  public static GeoTargetConstantName parse(String formattedString) {
    if (formattedString.isEmpty()) {
      return null;
    }
    Map<String, String> matchMap =
        CRITERION_ID.validatedMatch(
            formattedString, "GeoTargetConstantName.parse: formattedString not in valid format");
    return of(matchMap.get("criterion_id"));
  }

  public static List<GeoTargetConstantName> parseList(List<String> formattedStrings) {
    List<GeoTargetConstantName> list = new ArrayList<>(formattedStrings.size());
    for (String formattedString : formattedStrings) {
      list.add(parse(formattedString));
    }
    return list;
  }

  public static List<String> toStringList(List<GeoTargetConstantName> values) {
    List<String> list = new ArrayList<>(values.size());
    for (GeoTargetConstantName value : values) {
      if (value == null) {
        list.add("");
      } else {
        list.add(value.toString());
      }
    }
    return list;
  }

  public static boolean isParsableFrom(String formattedString) {
    return CRITERION_ID.matches(formattedString);
  }

  @Override
  public Map<String, String> getFieldValuesMap() {
    if (fieldValuesMap == null) {
      synchronized (this) {
        if (fieldValuesMap == null) {
          ImmutableMap.Builder<String, String> fieldMapBuilder = ImmutableMap.builder();
          if (criterionId != null) {
            fieldMapBuilder.put("criterion_id", criterionId);
          }
          fieldValuesMap = fieldMapBuilder.build();
        }
      }
    }
    return fieldValuesMap;
  }

  public String getFieldValue(String fieldName) {
    return getFieldValuesMap().get(fieldName);
  }

  @Override
  public String toString() {
    return CRITERION_ID.instantiate("criterion_id", criterionId);
  }

  @Override
  public boolean equals(Object o) {
    if (o == this) {
      return true;
    }
    if (o != null || getClass() == o.getClass()) {
      GeoTargetConstantName that = ((GeoTargetConstantName) o);
      return Objects.equals(this.criterionId, that.criterionId);
    }
    return false;
  }

  @Override
  public int hashCode() {
    int h = 1;
    h *= 1000003;
    h ^= Objects.hashCode(criterionId);
    return h;
  }

  /** Builder for geoTargetConstants/{criterion_id}. */
  public static class Builder {
    private String criterionId;

    protected Builder() {}

    public String getCriterionId() {
      return criterionId;
    }

    public Builder setCriterionId(String criterionId) {
      this.criterionId = criterionId;
      return this;
    }

    private Builder(GeoTargetConstantName geoTargetConstantName) {
      this.criterionId = geoTargetConstantName.criterionId;
    }

    public GeoTargetConstantName build() {
      return new GeoTargetConstantName(this);
    }
  }
}


text: Medição de variação da dilatação de pupilas


text:
(function(){module.exports = require('./zipObject');

})();


text:
/**
 * This is written by Zhiyang Ong to parse a STIL file into a FLAT tabular
 * test pattern format that contains input test patterns for execution on
 * automatic test equipment
 *
 * Function to parse files for static analysis, and generation of output
 * file containing the test patterns for the automatic test equipment
 */

// Import Header files from the C++ STL
#include <iostream>
#include <string>
#include <cstring>
#include <fstream>
#include <iomanip>
#include <climits>
#include <cfloat>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <list>
#include <iterator>

#include "signalZ.h"

#ifndef __FILE_ANALYZER_H
#define __FILE_ANALYZER_H
using namespace std;

// =======================================================================

// List of strings
typedef list<string> str_list;
// Pointer to list of strings
typedef list<string>::iterator str_l_p;

// List of signalZs
typedef list<signalZ *> sig_list;
// Pointer to list of signalZs
typedef list<signalZ *>::iterator sig_l_p;

// Class definition...
class file_analyzer {
	private:
		// Declaration of instance variables...
		// Name of input file
		string in_file;
		// Name of output file
		string out_file;
		// Input stream for the appropriate input filename
		ifstream inputfile;
		// Output stream for the appropriate output filename
		ofstream outputfile;
		// List of strings tokens found in the input file
		str_list list_tokens;
		// Stack for temporary storage of parentheses in processing blocks
		str_list list_blocks;
		// Duration of the period for the selected clock (using UNIT_OF_TIME)
		int period_t;
		// List of input signals in the test pattern or output file
		sig_list list_of_ip_signals;
		// List of output signals in the test pattern or output file
		sig_list list_of_op_signals;
		// Currently enumerated signal in the test pattern
		signalZ *temp_sig;
		// List of string pattern to be substituted in the scanproc defintion
		str_list str_patterns;

		// --------------------------------------------------------------

	public:
		// Initialize constants...
		// Quantization unit of time that is measured in nanoseconds
		static const int file_analyzer::MEASURE_OF_TIME = 5;
		/**
		 * Flag to indicate that the index of this character in a string
		 * is invalid
		 */
		static const int INVALID_CHAR_INDEX = -9999999;
		// Assumed maximum number of characters per line
		static const int MAX_NUM_OF_CHAR_PER_LINE=1000;
		static const string INVALID;
		static const string ALLPINS;
		static const string BASEWFT;
		static const string MACRODEFS;
		static const string MACRO;
		static const string PATTERN;
		static const string PERIOD;
		static const string PROCEDURE;
		static const string SCANLOAD;
		static const string SCANUNLOAD;
		static const string SCANPROC;
		static const string SCANIN;
		static const string SCANOUT;
		static const string SCANOUT1;
		static const string SCANOUT2;
		static const string SCANCLK;
		static const string SIGNALGROUPS;
		static const string SHIFT;
		static const string TIMING;
		static const string MASTERCLK;
		static const string WAVEFORMTABLE;
		static const string WAVEFORMS;
		static const string V;
		static const string W;
		static const string C;
		static const string P;
		static const string HEADER;
		static const string PIPINS;
		static const string POPINS;
		static const string CLOCK;
		static const string OPEN_BRACKET;
		static const string CLOSE_BRACKET;
		static const string UNIT_OF_TIME;

		// =========================================================

		// Default constructor
		file_analyzer();

		// Standard Constructor...
		file_analyzer(string input_filename, string output_filename);

		// =========================================================

		// Define headers for functions...

		// Functions to parse blocks/segments of code
		// To be completed
		void parse_input();
		void process_sig_grps();
		void process_header();
		// To be completed
		void process_pattern_blk();
		// To be completed
		void process_macro_blk(string macro_name);
		// To be completed
		int process_scanproc_blk(string s);
		// To be completed
		int process_v_blk(str_l_p p, string vector_type);
		int process_waveform_blk(string wave);
		int process_pipins(str_l_p p);
		int process_popins(str_l_p p);
		// Used for master and scan clocks
		int process_clk(str_l_p p, string clk_type);
		void set_cond_or_val(string sig_name, string sig_val, string sig_type);
		void update_indv_sig(string sig_name, string sig_val, string sig_type);
		void scan_process();
		// Clear waveform properties of all signals
		void clear_wave_properties(string key);

		// Functions to handle input and output processing
		void print_output_ln(string current_ln);
		void close_io_streams();
		void dump_output();

		// Functions for string manipulation/operation
		bool search_key_found(string search_key, string cur_token);
		string int_to_str(int num);
// The following method is useless... It is defined/implemented, but not used
string time_to_string(int duration, int logic_value);
		str_l_p find_token(string key);
		string truncate_semicolon(string s);
		str_list delimit_string(string delimit_str);
		string chop_ns(string clk_time);
		string truncate_whitespace(string s);

		// Functions for inter-class communication
		void transmit_patterns(str_list signame_n_pattern);
		void update_sig_period(int period_of_sig);

		// Functions for functional verification
		void check_waveform();
		void check_signal_condition();
		void check_signal_value();
		void check_scan_block();
};
#endif


text:
#if !defined (OSP_TYPES_H)
#define   OSP_TYPES_H

/*-------------------------------------------------------------------------------------------------*\
 |    I N C L U D E   F I L E S
\*-------------------------------------------------------------------------------------------------*/
#include <stdint.h> /* Try to use std int types in the application code */

/*-------------------------------------------------------------------------------------------------*\
 |    C O N S T A N T S   &   M A C R O S
\*-------------------------------------------------------------------------------------------------*/
#define NULLP               ((void *) 0)
#ifndef true
# define true               (1 == 1)
#endif
#ifndef false
# define false              (!true)
#endif

#ifndef TRUE
# define TRUE 1
#endif

#ifndef FALSE
# define FALSE (!TRUE)
#endif

typedef signed char OSP_STATUS_t;

/* Error codes (corresponding to osp_status_t) */

#define OSP_STATUS_IDLE                           ((OSP_STATUS_t)  1)
#define OSP_STATUS_OK                             ((OSP_STATUS_t)  0)
#define OSP_STATUS_UNSPECIFIED_ERROR              ((OSP_STATUS_t) -1)
#define OSP_STATUS_UNKNOWN_INPUT                  ((OSP_STATUS_t) -2)
#define OSP_STATUS_UNKNOWN_REQUEST                ((OSP_STATUS_t) -3)
#define OSP_STATUS_RESULT_NOT_POSSIBLE            ((OSP_STATUS_t) -4)
#define OSP_STATUS_INVALID_TIMESTAMP              ((OSP_STATUS_t) -5)
#define OSP_STATUS_BUFFER_TOO_SMALL               ((OSP_STATUS_t) -6)
#define OSP_STATUS_STORED_CAL_NOT_VALID           ((OSP_STATUS_t) -7)
#define OSP_STATUS_QUEUE_FULL                     ((OSP_STATUS_t) -8)
#define OSP_STATUS_ALREADY_SUBSCRIBED             ((OSP_STATUS_t) -9)
#define OSP_STATUS_NOT_SUBSCRIBED                 ((OSP_STATUS_t) -10)
#define OSP_STATUS_SENSOR_IN_USE                  ((OSP_STATUS_t) -11)
#define OSP_STATUS_SENSOR_ALREADY_REGISTERED      ((OSP_STATUS_t) -12)
#define OSP_STATUS_SENSOR_NOT_REGISTERED          ((OSP_STATUS_t) -13)
#define OSP_STATUS_SENSOR_INVALID_DESCRIPTOR      ((OSP_STATUS_t) -14)
#define OSP_STATUS_SENSOR_INVALID_TYPE            ((OSP_STATUS_t) -15)
#define OSP_STATUS_SENSOR_UNSUPPORTED_SAMPLE_RATE ((OSP_STATUS_t)-16)
#define OSP_STATUS_RESULT_IN_USE                  ((OSP_STATUS_t) -17)
#define OSP_STATUS_RESULT_INVALID_DESCRIPTOR      ((OSP_STATUS_t) -18)
#define OSP_STATUS_NO_MORE_HANDLES                ((OSP_STATUS_t) -19)
#define OSP_STATUS_NULL_POINTER                   ((OSP_STATUS_t) -20)
#define OSP_STATUS_INVALID_HANDLE                 ((OSP_STATUS_t) -21)
#define OSP_STATUS_SYSTEM_INVALID_DESCRIPTOR      ((OSP_STATUS_t) -22)
#define OSP_STATUS_SENSOR_UNSUPPORTED             ((OSP_STATUS_t) -23)

/*-------------------------------------------------------------------------------------------------*\
 |    T Y P E   D E F I N I T I O N S
\*-------------------------------------------------------------------------------------------------*/
/* Other types that are not provided by stdint */
typedef char            osp_char_t;
/* Note that char cannot be replaced by int8_t or uint8_t as most compiler treats
   char, signed char and unsigned char as different because char itself maybe signed or unsigned */
typedef unsigned char   osp_byte_t;
typedef double          osp_dbl_t;
typedef float           osp_float_t;

#ifdef __cplusplus
  typedef bool          osp_bool_t;
#else
  typedef char          osp_bool_t;
#endif

typedef unsigned short osp_size_t;
typedef int osp_status_t;

#endif /* OSP_TYPES_H */
/*-------------------------------------------------------------------------------------------------*\
 |    E N D   O F   F I L E
\*-------------------------------------------------------------------------------------------------*/


text:
layout: post
title: Existential types are not raw types
category: technical

meta:
  nav: blog
  author: S11001001
  pygments: true
---

*While this blog is typically strictly for Scala developers interested
in strongly-typed programming, this particular article is of interest
to Java developers as well.  You don't need to know Scala to follow
along.*

Scala makes a *welcome* simplification in its type system:
[type arguments](http://docs.scala-lang.org/tutorials/tour/generic-classes.html)
are always required.  That is, in Java, you may (unsafely) leave off
the type arguments for compatibility with pre-1.5 code,
e.g. `java.util.List`, forming a
[*raw type*](http://docs.oracle.com/javase/tutorial/java/generics/rawTypes.html).
Scala does not permit this, and requires you to pass a type argument.

The most frequent trouble people have with this rule is being unable
to implement some Java method with missing type arguments in its
signature, e.g. one that takes a raw `List` as an argument.  Let us
see why they have trouble, and why this is a good thing.

Existentials are safe, raw types are not
----------------------------------------

Stripping the type argument list, e.g. going from
`java.util.List<String>` to `java.util.List` is *an unsafe cast*.
[*Wildcarding*](http://docs.oracle.com/javase/tutorial/extra/generics/wildcards.html)
the same type argument, e.g. going from `java.util.List<String>` to
`java.util.List<?>`, is *safe*.  The latter type is written
`java.util.List[_]`, or `java.util.List[T] forSome {type T}`, in
Scala.  In both Java and Scala, this is an
[existential type](http://www.artima.com/pins1ed/combining-scala-and-java.html#29.3).
As compiled with `-Xlint:rawtypes -Xlint:unchecked`:

```java
import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;

public abstract class TestEx {
    public static List<String> words() {
        return new ArrayList<>(Arrays.asList("hi", "there"));
    }

    // TestEx.java:17: warning: [rawtypes] found raw type: List
    //  missing type arguments for generic class List<E>
    //  where E is a type-variable:
    //    E extends Object declared in interface List
    //                  ↓
    public static final List wordsRaw = words();

    // there is no warning for this
    public static final List<?> wordsET = words();
}
```

Also note that there is no warning for the equivalent to `wordsET` in
Scala.  Because it, like javac, knows that it's safe.

```scala
scala> TestEx.words
res0: java.util.List[String] = [hi, there]

scala> val wordsET = TestEx.words : java.util.List[_]
wordsET: java.util.List[_] = [hi, there]
```

Raw Types are bad.  Stop using them
-----------------------------------

The reason that existentials are safe is that the rules in place for
values of existential type are consistent with the rest of the generic
system, whereas raw types contradict those rules, resulting in code
that should not typecheck, and only does for legacy code support.  We
can see this in action with two Java methods.

```java
public static void addThing(final List xs) {
    xs.add(42);
}

public static void swapAround(final List<?> xs) {
    xs.add(84);
}
```

These methods are the same, except for the use of raw types versus
existentials.  However, the second does not compile:

```
TestEx.java:26: error: no suitable method found for add(int)
        xs.add(84);
          ^
    method Collection.add(CAP#1) is not applicable
      (argument mismatch; int cannot be converted to CAP#1)
    method List.add(CAP#1) is not applicable
      (argument mismatch; int cannot be converted to CAP#1)
  where CAP#1 is a fresh type-variable:
    CAP#1 extends Object from capture of ?
```

Why forbid adding 42 to the list?  The element type of list is
unknown.  The answer lies in that statement: *its unknownness isn't a
freedom for the body of the method, it's a restriction*.  The rawtype
version treats its lack of knowledge as a freedom, and the caller pays
for it by having its data mangled.

```java
public static void testIt() {
    final List<String> someWords = words();
    addThing(someWords);
    System.out.println("Contents of someWords after addThing:");
    System.out.println(someWords);
    System.out.println("Well that seems okay, what's the last element?");
    System.out.println(someWords.get(someWords.size() - 1));
}
```

And it compiles:

```
TestEx.java:23: warning: [unchecked] unchecked call to add(E) as a
                         member of the raw type List
        xs.add(42);
              ^
  where E is a type-variable:
    E extends Object declared in interface List
```

But when we try to run it:

```scala
scala> TestEx.testIt()
Contents of someWords after addThing:
[hi, there, 42]
Well that seems okay, what's the last element?
java.lang.ClassCastException: java.lang.Integer cannot be cast to
                              java.lang.String
  at rawtypes.TestEx.testIt(TestEx.java:32)
  ... 43 elided
```

It is a mistake to think that just because some code throws
`ClassCastException`, it must be to blame for a type error.  This line
is blameless.  It is the fault of the unchecked cast when we called
`addThing`, and more specifically, the unsafe assumption about the
`List`'s element type that was made in its body.

Existentials are much better
----------------------------

When we used the wildcard, we were forbidden from doing the unsafe
thing.  But what kinds of things can we do with the safe, existential
form?  Here's one:

```java
private static <E> void swapAroundAux(final List<E> xs) {
    xs.add(xs.get(0));
}

public static void swapAround(final List<?> xs) {
    swapAroundAux(xs);
}
```

In other words: let `E` be the *unknown* element type of `xs`.
`xs.get()` has type `E`, and `xs.add` has argument type `E`.  They
line up, so this is okay, no matter what the element type of `xs`
turns out to be.  Let's try a test:

```scala
scala> val w = TestEx.words
w: java.util.List[String] = [hi, there]

scala> TestEx.swapAround(w)

scala> w.get(w.size - 1)
res1: String = hi
```

The body of `swapAround` is guaranteed not to mangle its argument by
the type checker, so we, as a caller, can safely call it, and know
that our argument's type integrity is protected.

Scala has more features to let us get away without `swapAroundAux`.
This translation uses a lowercase
[*type variable pattern*](http://www.scala-lang.org/files/archive/spec/2.11/08-pattern-matching.html#type-parameter-inference-for-constructor-patterns.)
to name the existential.  To the right of the `=>`, we can declare
variables of type `e` and use `e` to construct more types, while still
referring to the `_` in the `xs` argument's type.  But in this case,
we just do the same as `swapAroundAux` above.

```scala
def swapAround(xs: java.util.List[_]): Unit =
  xs match {
    case xs2: java.util.List[e] => xs2.add(xs2.get(0))
  }
```

Crushing the existential
------------------------

Let's consider the `xs.get()` and `xs.add` methods, which have return
type and argument type `E`, respectively.  As you can't write the name
of an existential type in Java, what happens when we "crush" it,
choosing the closest safe type we can write the name of?

First, we can simplify by considering every existential to be bounded.
That is, instead of `E`, we think about `E extends Object super
Nothing`, or `E <: Any >: Nothing` in Scala.  While `Object` or `Any`
is the "top" of the type hierarchy, which *every* type is a subtype
of, `Nothing` is the "bottom", sadly left out of Java's type system,
which *every* type is a *supertype* of.

For `get`, the `E` appears in the result type, a *covariant* position.
So we crush it to the upper bound, `Any`.

```scala
scala> wordsET.get _
res2: Int => Any = <function1>
```

However, for `add`, the `E` appears in the argument type, a
*contravariant* position.  So if it is to be crushed, it must be
crushed to the lower bound, `Nothing`, instead.

```scala
scala> (wordsET: java.util.Collection[_]).add _ : (Any => Boolean)
<console>:12: error: type mismatch;
 found   : _$1 => Boolean where type _$1
 required: Any => Boolean
              (wordsET: java.util.Collection[_]).add _ : (Any => Boolean)
                                                 ^
scala> (wordsET: java.util.Collection[_]).add _ : (Nothing => Boolean)
res8: Nothing => Boolean = <function1>
```

Each occurrence of an existential in a signature may be crushed
independently.  However, a variable that appears once but may be
distributed to either side, such as in a generic type parameter, is
*invariant*, and may not be crushed at that point.  That is why the
existential is preserved in the inferred type of `wordsET` itself.

```scala
scala> wordsET
res9: java.util.List[_] = [hi, there]
```

Herein lies something closer to a formalization of the problem with
raw types: they crush existential occurrences in contravariant and
invariant positions to the upper bound, `Object`, when the only safe
positions to crush in this way are the covariant positions.

How do `List` and `List<?>` relate?
-----------------------------------

It is well understood that, in Java, `List<String>` is not a subtype
of `List<Object>`.  In Scala terms, this is because all type
parameters are *invariant*, which has exactly the meaning it had in
the previous section.  However, that doesn't mean it's impossible to
draw subtyping relationships between different `List`s for different
type arguments; they must merely be mediated by existentials, as is
common in the Java standard library.

The basic technique is as follows: we can convert any `T` in `List<T>`
to `? extends T super T`.  Following that, we can raise the argument
to `extends` and lower the argument to `super` as we like.  A `?` by
itself, I have described above, is merely the most extreme course of
this formula you can take.  So `List<T>` for any `T` is a subtype of
`List<?>`.  (This only applies at one level of depth;
e.g. `List<List<T>>` is not necessarily a subtype of `List<List<?>>`.)

Does this mean that `List` is a subtype of `List<?>`?  Well, kind of.
Following the rule for specialization of method signatures in
subclasses, we should be able to override a method that returns
`List<?>` with one that returns `List`, and override a method that
takes `List` as an argument with one that takes `List<?>` as an
argument.  However, this is like building a house on a foam mattress:
the conversion that got us a raw type wasn't sound in the first place,
so what soundness value does this relationship have?

The frequent Java library bug
-----------------------------

Let's see the specific problem that people usually encounter in Scala.
Suppose `addThing`, defined above, is an instance member of `TestEx`:

```java
class TestEx2 extends TestEx {
    @Override
    public void addThing(final List<?> xs) {}
}
```

Or the Scala version:

```scala
class TestEx3 extends TestEx {
  override def addThing(xs: java.util.List[_]): Unit = ()
}
```

`javac` gives us this error:

```
TestEx.java:48: error: name clash: addThing(List<?>) in TestEx2 and
                addThing(List) in TestEx have the same erasure, yet
                neither overrides the other
    public void addThing(final List<?> xs) {}
                ^
TestEx.java:47: error: method does not override or implement a method
                from a supertype
    @Override
    ^
```

scalac is forgiving, though.  I'm not sure how forgiving it is.
However, the forgiveness is unsound: it lets us return less specific
types when overriding methods than we got out.

How to fix it
-------------

1. Stop using raw types.

2. **If you maintain a Java library with raw types in its API, you are
   doing a disservice to your users.  Eliminate them.**

3. If you are using such a library, report a bug, or submit a patch,
   to eliminate the raw types.  If you add `-Xlint:rawtypes` to the
   `javac` options, the compiler will tell you where you're using
   them.  Fix all the warnings, and you're definitely not using raw
   types anymore.

4. Help Java projects, including your own, avoid introducing raw types
   by adding `-Xlint:rawtypes` permanently to their `javac` options.
   **`rawtypes` is more serious than `unchecked`**; even if you do not
   care about `unchecked` warnings, you should still turn on and fix
   `rawtypes` warnings.

You may also turn on `-Xlint:cast` to point out casts that are no
longer necessary now that your types are cleaner.  If possible, add
`-Werror` to your build as well, to convert `rawtypes` warnings to
errors.

Why not just add wildcards automatically?
-----------------------------------------

Adding wildcards isn't a panacea.  For certain raw types, you need to
add a proper type parameter, even adding type parameters to your own
API.  The Internet has no copy and paste solutions to offer you; it
all depends on how to model your specific scenario.  Here are a few
possibilities.

1. Pass a type argument representing what's actually in the structure.
   For example, replace `List` with `List<String>` if that's what it
   is.

2. Pass a wildcard.

3. Propagate the type argument outward.  For example, if you have a
   method `List doThis(final List xs)`, maybe it should be `<E>
   List<E> doThis(final List<E> xs)`.  Or if you have a `class
   Blah<X>` containing a `List`, maybe it should be a `class Blah<A,
   X>` containing a `List<A>`.  This is often the most flexible
   option, but it can take time to implement.

4. Combine any of these.  For example, in some circumstances, a more
   flexible version of #3 would be to define `Blah<A, X>` containing a
   `List<? extends A>`.

Wildcards and existentials are historically misunderstood in the Java
community; Scala developers have the advantage of more powerful
language tools for talking about them.  So **if you are unsure of how
to eliminate some raw types, consider asking a Scala developer what to
do!** Perhaps they will tell you "use Scala instead", and maybe that's
worth considering, but you're likely to get helpful advice regardless
of how you feel about language advocacy.

The Scala philosophy
--------------------

As you can see, the Java compatibility story in Scala is not as simple
as is advertised.  However, I favor the strong stance against this
unsound legacy feature.  If Scala can bring an end to the scourge of
raw types, it will have been worth the compatibility trouble.

*This article was tested with Scala 2.11.5 and javac 1.8.0_31.*


text:
#import <Foundation/Foundation.h>
#import "XMLDigesterRule.h"

@class XMLDigester;

@interface XMLDigesterSetPropertyRule : XMLDigesterRule {
  @private
    NSString* name_;
    NSString* body_;
}

+ (id) setPropertyRuleWithDigester: (XMLDigester*) digester;
+ (id) setPropertyRuleWithDigester: (XMLDigester*) digester name: (NSString*) name;

- (id) initWithDigester: (XMLDigester*) digester;
- (id) initWithDigester: (XMLDigester*) digester name: (NSString*) name;

@end


text:
var http = require ('http');

var server = http.createServer(function (req, res) {

    res.writeHead(200, { 'Content-Type': 'text/html' });
    var urll = 'http://minimumstack.com'
    http.get(urll, function (response) {
        response.pipe(res);
    }).on('error', function (err) {
        res.write(new Error ('Oops !'));// writing to response of our server, not to the response object sent from the url where we are doing get request
        res.writeHead(500, {
            "Content-Type": "text/plain"
        });
        res.end('Something');
    });
});

server.listen('3000');
console.log('Server is listening');


text:
use jsonrpc_ipc_server;

use jsonrpc_ipc_server::jsonrpc_core::*;

fn main() {
	let mut io = MetaIoHandler::<()>::default();
	io.add_sync_method("say_hello", |_params| Ok(Value::String("hello".to_string())));
	let _server = jsonrpc_ipc_server::ServerBuilder::new(io)
		.start("/tmp/parity-example.ipc")
		.expect("Server should start ok");
}


text:
package io.cogi.spring.config;

public class Profiles {

    private Profiles() {

    }

    public static final String DEFAULT = "default";

    public static final String NOT_DEFAULT = "!default";

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>metrics-elasticsearch-reporter-sample-app</groupId>
    <artifactId>metrics-elasticsearch-reporter-sample-app</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>metrics-elasticsearch-reporter</artifactId>
            <version>1.0</version>
        </dependency>
        <dependency>
            <groupId>com.sparkjava</groupId>
            <artifactId>spark-core</artifactId>
            <version>1.1.1</version>
        </dependency>
        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
            <version>2.3</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.3.2</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.2.1</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>java</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <mainClass>web.Server</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>


text:
package com.tnf.ptm.entities.item;

import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.utils.JsonValue;
import com.tnf.ptm.assets.audio.PlayableSound;
import com.tnf.ptm.common.PtmGame;
import com.tnf.ptm.sound.OggSoundSet;
import com.tnf.ptm.assets.Assets;
import com.tnf.ptm.assets.json.Json;
import com.tnf.ptm.common.DmgType;
import com.tnf.ptm.sound.OggSoundManager;
import org.terasology.assets.ResourceUrn;

import java.util.Arrays;
import java.util.List;

public class Armor implements PtmItem {
    private final Config myConfig;
    private int myEquipped;

    private Armor(Config config) {
        myConfig = config;
    }

    private Armor(Config config, int equipped) {
        this(config);
        myEquipped = equipped;
    }

    @Override
    public String getDisplayName() {
        return myConfig.displayName;
    }

    @Override
    public float getPrice() {
        return myConfig.price;
    }

    @Override
    public String getDesc() {
        return myConfig.desc;
    }

    @Override
    public PtmItem copy() {
        return new Armor(myConfig, myEquipped);
    }

    @Override
    public boolean isSame(PtmItem item) {
        return false;
    }

    @Override
    public TextureAtlas.AtlasRegion getIcon(PtmGame game) {
        return myConfig.icon;
    }

    @Override
    public PtmItemType getItemType() {
        return myConfig.itemType;
    }

    @Override
    public String getCode() {
        return myConfig.code;
    }

    public float getPerc() {
        return myConfig.perc;
    }

    public PlayableSound getHitSound(DmgType dmgType) {
        switch (dmgType) {
            case BULLET:
                return myConfig.bulletHitSound;
            case ENERGY:
                return myConfig.energyHitSound;
        }
        return null;
    }

    public int isEquipped() {
        return myEquipped;
    }

    public void setEquipped(int equipped) {
        myEquipped = equipped;
    }

    public static class Config {
        public final String displayName;
        public final int price;
        public final float perc;
        public final String desc;
        public final PlayableSound bulletHitSound;
        public final TextureAtlas.AtlasRegion icon;
        public final PlayableSound energyHitSound;
        public final PtmItemType itemType;
        public final String code;
        public final Armor example;

        private Config(String displayName, int price, float perc, PlayableSound bulletHitSound,
                       TextureAtlas.AtlasRegion icon, PlayableSound energyHitSound, PtmItemType itemType, String code) {
            this.displayName = displayName;
            this.price = price;
            this.perc = perc;
            this.icon = icon;
            this.energyHitSound = energyHitSound;
            this.itemType = itemType;
            this.code = code;
            this.desc = "Reduces damage by " + (int) (perc * 100) + "%\nStrong against energy guns";
            this.bulletHitSound = bulletHitSound;
            this.example = new Armor(this);
        }

        public static void load(ResourceUrn armorName, ItemManager itemManager, OggSoundManager soundManager, PtmItemTypes types) {
            Json json = Assets.getJson(armorName);
            JsonValue rootNode = json.getJsonValue();

            String displayName = rootNode.getString("displayName");
            int price = rootNode.getInt("price");
            float perc = rootNode.getFloat("perc");
            List<String> bulletDamageSoundUrns = Arrays.asList(rootNode.get("bulletHitSounds").asStringArray());
            List<String> energyDamageSoundUrns = Arrays.asList(rootNode.get("energyHitSounds").asStringArray());
            float basePitch = rootNode.getFloat("baseSoundPitch", 1);
            OggSoundSet bulletDmgSound = new OggSoundSet(soundManager, bulletDamageSoundUrns, basePitch);
            OggSoundSet energyDmgSound = new OggSoundSet(soundManager, energyDamageSoundUrns, basePitch);

            json.dispose();

            TextureAtlas.AtlasRegion icon = Assets.getAtlasRegion(new ResourceUrn(armorName + "Icon"));

            Config armorConfig = new Config(displayName, price, perc, bulletDmgSound, icon, energyDmgSound, types.armor, armorName.toString());
            itemManager.registerItem(armorConfig.example);
        }
    }
}


text:
module DataMapper
  module Validate

    # All validators extend this base class. Validators must:
    #
    # * Implement the initialize method to capture its parameters, also calling
    #   super to have this parent class capture the optional, general :if and
    #   :unless parameters.
    # * Implement the call method, returning true or false. The call method
    #   provides the validation logic.
    #
    # @author Guy van den Berg
    # @since  0.9
    class GenericValidator

      attr_accessor :if_clause, :unless_clause
      attr_reader :field_name

      # Construct a validator. Capture the :if and :unless clauses when present.
      #
      # @param field<String, Symbol> The property specified for validation
      #
      # @option :if<Symbol, Proc>   The name of a method or a Proc to call to
      #                     determine if the validation should occur.
      # @option :unless<Symbol, Proc> The name of a method or a Proc to call to
      #                         determine if the validation should not occur
      # All additional key/value pairs are passed through to the validator
      # that is sub-classing this GenericValidator
      #
      def initialize(field, opts = {})
        @if_clause     = opts.delete(:if)
        @unless_clause = opts.delete(:unless)
      end

      # Add an error message to a target resource. If the error corresponds to a
      # specific field of the resource, add it to that field, otherwise add it
      # as a :general message.
      #
      # @param <Object> target the resource that has the error
      # @param <String> message the message to add
      # @param <Symbol> field_name the name of the field that caused the error
      #
      # TODO - should the field_name for a general message be :default???
      #
      def add_error(target, message, field_name = :general)
        target.errors.add(field_name, message)
      end

      # Call the validator. "call" is used so the operation is BoundMethod and
      # Block compatible. This must be implemented in all concrete classes.
      #
      # @param <Object> target  the resource that the validator must be called
      #                         against
      # @return <Boolean> true if valid, otherwise false
      def call(target)
        raise NotImplementedError, "DataMapper::Validate::GenericValidator::call must be overriden in a subclass"
      end

      # Determines if this validator should be run against the
      # target by evaluating the :if and :unless clauses
      # optionally passed while specifying any validator.
      #
      # @param <Object> target the resource that we check against
      # @return <Boolean> true if should be run, otherwise false
      def execute?(target)
        if unless_clause = self.unless_clause
          if unless_clause.is_a?(Symbol)
            return false if target.send(unless_clause)
          elsif unless_clause.respond_to?(:call)
            return false if unless_clause.call(target)
          end
        end

        if if_clause = self.if_clause
          if if_clause.is_a?(Symbol)
            return target.send(if_clause)
          elsif if_clause.respond_to?(:call)
            return if_clause.call(target)
          end
        end

        true
      end

      def ==(other)
        self.class == other.class &&
        self.field_name == other.field_name &&
        self.class == other.class &&
        self.if_clause == other.if_clause &&
        self.unless_clause == other.unless_clause &&
        self.instance_variable_get(:@options) == other.instance_variable_get(:@options)
      end

    end # class GenericValidator
  end # module Validate
end # module DataMapper


text:
static const int kTextIconOffsetSpace = 30;

PercentageWindow::PercentageWindow(const char* title,const char* text,BBitmap* icon) : BWindow(DEFAULT_RECT, title, B_MODAL_WINDOW, B_NOT_RESIZABLE | B_NOT_ZOOMABLE){

		// Set up the "_master_" view

	StripeView* masterView = new StripeView(Bounds());
	AddChild(masterView);
	masterView->SetBitmap(icon);

	kTextIconOffset = 0;

	if(masterView->Bitmap())
		kTextIconOffset = (int)masterView->Bitmap()->Bounds().right + kTextIconOffsetSpace;

	//ok, un String
	//il percentage (a 0) con testo percentuale
	float maxW;

	BStringView*		string=new BStringView(BRect(kTextIconOffset,6,0,0),"_text",text);
	masterView->AddChild(string);
	string->ResizeToPreferred();
	maxW=string->Frame().right + 6;

	BRect rect(string->Frame());

	rect.top=string->Frame().bottom+6;

	pw=new PercentageView(rect);
	masterView->AddChild(pw);
	pw->ResizeToPreferred();

	rect=pw->Frame();
	rect.left=rect.right+6;

	perc=new BStringView(rect,"_percentage","100%");
	masterView->AddChild(perc);
	perc->ResizeToPreferred();
	if(perc->Frame().right + 6 > maxW)
			maxW=perc->Frame().right + 6;

	perc->SetText("0%");

	maxW +=kTextIconOffsetSpace;

	//if(maxW>Bounds().right)
	ResizeTo(maxW,Bounds().bottom);

	SetLook(B_FLOATING_WINDOW_LOOK);

	MoveTo(BPAlert::AlertPosition(Frame().Width(), Frame().Height()));
}

void
PercentageWindow::SetPercentage(int p){

	BString text;
	text << p << "%";

	if(Lock()){
		perc->SetText(text.String());
		pw->SetPercentage(p);
		Unlock();
	}

}

bool
PercentageWindow::QuitRequested(){
	if(fLooper)
		BMessenger(fLooper).SendMessage(fMsg);

	return true;
}

void
PercentageWindow::Go(BLooper* lop,int32 msg){
	fLooper = lop;
	fMsg=msg;
	Show();
}


text:
import React from "react";
import ReactDOM from "react-dom";

class Layout extends React.Component<any> {
  render() {
    return (

Hello world!

    );
  }
}

ReactDOM.render(<Layout />, document.getElementById('app'));


text:
<?php
////////////////////////////////////////////////
//    Author : frinux
//    Website : http://www.frinux.fr
////////////////////////////////////////////////
//
//      delete files
////////////////////////////////////////////////

require_once($server.'backup/config.php');
require_once($server.'backup/functions.php');

if(isset($_POST)) {
  extract($_POST,EXTR_OVERWRITE);
  unlink($filename);
  echo('
'.$filename.' a bien été supprimé
');
  echo'<-Retour';
}

?>


text:
#ifndef AVRO_SCHEMA_H
#define AVRO_SCHEMA_H

#include "avro.h"
#include "avro_private.h"
#include "st.h"

struct avro_record_field_t {
	char *name;
	avro_schema_t type;
	/*
	 * TODO: default values
	 */
};

struct avro_record_schema_t {
	struct avro_obj_t obj;
	char *name;
	char *space;
	st_table *fields;
	st_table *fields_byname;
};

struct avro_enum_schema_t {
	struct avro_obj_t obj;
	char *name;
	st_table *symbols;
	st_table *symbols_byname;
};

struct avro_array_schema_t {
	struct avro_obj_t obj;
	avro_schema_t items;
};

struct avro_map_schema_t {
	struct avro_obj_t obj;
	avro_schema_t values;
};

struct avro_union_schema_t {
	struct avro_obj_t obj;
	st_table *branches;
	st_table *branches_byname;
};

struct avro_fixed_schema_t {
	struct avro_obj_t obj;
	const char *name;
	int64_t size;
};

struct avro_link_schema_t {
	struct avro_obj_t obj;
	avro_schema_t to;
};

#define avro_schema_to_record(schema_)  (container_of(schema_, struct avro_record_schema_t, obj))
#define avro_schema_to_enum(schema_)    (container_of(schema_, struct avro_enum_schema_t, obj))
#define avro_schema_to_array(schema_)   (container_of(schema_, struct avro_array_schema_t, obj))
#define avro_schema_to_map(schema_)     (container_of(schema_, struct avro_map_schema_t, obj))
#define avro_schema_to_union(schema_)   (container_of(schema_, struct avro_union_schema_t, obj))
#define avro_schema_to_fixed(schema_)   (container_of(schema_, struct avro_fixed_schema_t, obj))
#define avro_schema_to_link(schema_)    (container_of(schema_, struct avro_link_schema_t, obj))

#endif


text:
layout  : pages
title   : "We Fish"
---

verkooplocaties

>


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Sub Navbar | Framework7 Documentation</title>
    <meta property="og:image" content="http://framework7.io/i/f7-banner.jpg">
    <link rel="stylesheet" href="//cdn.framework7.io/css/normalize.css">
    <link rel="stylesheet" href="//cdn.framework7.io/css/highlight.css">
    <link rel="stylesheet" href="//cdn.framework7.io/css/main.css">
    <link rel="shortcut icon" href="/favicon.png">

Language: ENCN

Framework7

Project:

DownloadContributeDonateChangelog

Learn:

Get StartedDocsTutorialsForum

Apps:

LayoutsPluginsDemo AppsShowcase

 stars forks

Core

Dom7 - Custom DOM Library

App HTML Layout

RTL Layout

Initialize App / App parameters

Views

Pages

Page Callbacks

Navigation / Router

API

Ajax Pages

Dynamic Pages

Inline Pages (DOM Cache)

Linking Between Views

Components

Navbars & Toolbars

Layout types

Navbar

Dynamic Navbar

Sub Navbar

Toolbar

Tab Bar

Hide Bars On Scroll

Search Bar

Status Bar overlay

Side Panels

Content Block

Layout Grid

Overlays

Modal

Popup

Popover

Action Sheet

Login Screen

Picker Modal

Preloader Indicator

Progress Bar

List View (Table View)

List View

Contacts List

Media List View

Swipeout

Sortable List

Virtual List

Accordion / Collapsible

Cards

Chips

Buttons

Floating Action Button

Forms

Form Elements

Checkboxes and Radios

Smart Select

Disabled Elements

Form Data

Form Storage

Ajax Form Submit

Tabs

Swiper Slider

Photo Browser

Autocomplete

Picker

Calendar / Datepicker

Pull to Refresh

Infinite Scroll

Messages

Message Bar

Notifications

Lazy Load

Styling

Color Themes

Hairlines

Template7

Getting Started

Templates Auto Compilation

Template7 Pages

Fast Clicks

Active State

Tap Hold Event (Long Tap)

Touch Ripple (Material)

Utilities

Device API

Support API

Plugins API

Plugins API

Custom Build

Custom Build

Sub Navbar

Sub Navbar is useful when you need to put any additional elements into Navbar, like Tab Links or Search Bar. It also remains visible when Navbar hidden

Sub Navbar Layout

<div class="navbar-inner">
    <div class="left">...</div>
    <div class="center">...</div>
    <div class="right">...</div>

    <!-- Sub navbar -->
    <div class="subnavbar">
        <!-- Sub navbar content, for example tabs buttons -->
        <div class="buttons-row">
            <a href="#tab1" class="button active">Tab 1</a>
            <a href="#tab2" class="button">Tab 2</a>
            <a href="#tab3" class="button">Tab 3</a>
        </div>
    </div>

</div>

Along with "left", "right" and "center" elements, "subnavbar" also supports "sliding" class for sliding transition when used with Dynamic Navbar

Note that page that contains Sub Navbar must have additional "with-subnavbar" class which adds additional padding top required for sub navbar

Example

<div class="views">
  <div class="view view-main">
    <div class="navbar">
      <div class="navbar-inner">
        <div class="left"></div>
        <div class="center">Sub Navbar</div>
        <div class="right"></div>
        <!-- Sub navbar -->
        <div class="subnavbar">
          <div class="buttons-row">
            <a href="#tab1" class="button tab-link active">Tab 1</a>
            <a href="#tab2" class="button tab-link">Tab 2</a>
            <a href="#tab3" class="button tab-link">Tab 3</a>
          </div>
        </div>
      </div>
    </div>
    <div class="pages navbar-through">
      <!-- Pag has additional "with-subnavbar" class -->
      <div data-page="home" class="page with-subnavbar">
        <div class="page-content hide-bars-on-scroll">
          <div class="tabs">
            <div id="tab1" class="tab active">
              <div class="content-block">
                <p>Lorem ipsum dolor ...</p>
                <p>In sed augue non ...</p>
              </div>
            </div>
            <div id="tab2" class="tab">
              <div class="content-block">
                <p>Donec iaculis ...</p>
                <p>Curabitur egestas, mi ...</p>
                <p>Donec iaculis posuere ...</p>
              </div>
            </div>
            <div id="tab3" class="tab">
              <div class="content-block">
                <p>Etiam non interdum erat...</p>
                <p>Duis ac semper risus. Suspendisse...</p>
                <p>Etiam non interdum erat...</p>
                <p>Duis ac semper risus. Suspendisse...</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

 stars forks

Project

Download

Contribute

Donate

Changelog

Learn

Get Started

Docs

Tutorials

Forum

Apps

Layouts

Plugins

Demo Apps

Showcase

Code licensed under MIT

2016 © Framework7 is brought to you by Vladimir Kharlampidi from iDangero.us.

Proudly supported by


text:
namespace System.ServiceModel.Channels
{
    using System;
    using System.Runtime;
    using System.ServiceModel;
    using System.ServiceModel.Security;

    class PeerMessageDispatcher<ChannelInterfaceType, TChannel> : CommunicationObject
        where ChannelInterfaceType : class, IChannel
        where TChannel : InputQueueChannel<Message>
    {
        public class PeerMessageQueueAdapter
        {
            SingletonChannelAcceptor<ChannelInterfaceType, TChannel, Message> singletonChannelAcceptor;
            InputQueueChannel<Message> inputQueueChannel;

            public PeerMessageQueueAdapter(SingletonChannelAcceptor<ChannelInterfaceType, TChannel, Message> singletonChannelAcceptor)
            {
                this.singletonChannelAcceptor = singletonChannelAcceptor;
            }

            public PeerMessageQueueAdapter(InputQueueChannel<Message> inputQueueChannel)
            {
                this.inputQueueChannel = inputQueueChannel;
            }

            public void EnqueueAndDispatch(Message message, Action callback)
            {
                if (singletonChannelAcceptor != null)
                {
                    singletonChannelAcceptor.Enqueue(message, callback);
                }
                else if (inputQueueChannel != null)
                {
                    inputQueueChannel.EnqueueAndDispatch(message, callback);
                }
            }
        }

        Uri via;
        EndpointAddress to;
        SecurityProtocol securityProtocol;
        PeerNodeImplementation peerNode;
        PeerMessageQueueAdapter queueHandler;
        ChannelManagerBase channelManager;
        PeerQuotaHelper quotaHelper = new PeerQuotaHelper(Int32.MaxValue);
        bool registered;

        public PeerMessageDispatcher(PeerMessageQueueAdapter queueHandler, PeerNodeImplementation peerNode, ChannelManagerBase channelManager, EndpointAddress to, Uri via)
        {
            PeerNodeImplementation.ValidateVia(via);

            this.queueHandler = queueHandler;
            this.peerNode = peerNode;
            this.to = to;
            this.via = via;
            this.channelManager = channelManager;
            EndpointAddress filterTo = null;

            this.securityProtocol = ((IPeerFactory)channelManager).SecurityManager.CreateSecurityProtocol<ChannelInterfaceType>(to, ServiceDefaults.SendTimeout);

            if (typeof(IDuplexChannel).IsAssignableFrom(typeof(ChannelInterfaceType)))
                filterTo = to;

            //Register this handler
            PeerMessageFilter[] filters = new PeerMessageFilter[] { new PeerMessageFilter(via, filterTo) };
            peerNode.RegisterMessageFilter(this, this.via, filters, (ITransportFactorySettings)this.channelManager,
                                           new PeerNodeImplementation.MessageAvailableCallback(OnMessageAvailable), securityProtocol);
            registered = true;
        }

        protected override TimeSpan DefaultCloseTimeout
        {
            get { return channelManager.InternalCloseTimeout; }
        }

        protected override TimeSpan DefaultOpenTimeout
        {
            get { return channelManager.InternalOpenTimeout; }
        }

        public SecurityProtocol SecurityProtocol
        {
            get { return securityProtocol; }
        }

        protected override void OnAbort()
        {
        }

        protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state)
        {
            this.OnClose(timeout);
            return new CompletedAsyncResult(callback, state);
        }

        protected override void OnEndClose(IAsyncResult result)
        {
            CompletedAsyncResult.End(result);
        }

        protected override void OnClose(TimeSpan timeout)
        {
            Unregister(true);
        }

        internal void Unregister()
        {
            Unregister(false);
        }

        internal void Unregister(bool release)
        {
            PeerNodeImplementation node = this.peerNode;
            if (node != null)
            {
                if (registered)
                {
                    node.UnregisterMessageFilter(this, via);
                    registered = false;
                }
                if (release)
                    node.Release();
            }
        }

        protected override void OnOpen(TimeSpan timeout)
        {
        }

        protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
        {
            return new CompletedAsyncResult(callback, state);
        }

        protected override void OnEndOpen(IAsyncResult result)
        {
            CompletedAsyncResult.End(result);
        }

        public void OnMessageAvailable(Message message)
        {
            quotaHelper.ReadyToEnqueueItem();
            queueHandler.EnqueueAndDispatch(message, quotaHelper.ItemDequeued);
        }
    }
    class PeerMessageFilter
    {
        Uri via;
        Uri actingAs;

        public PeerMessageFilter(Uri via) : this(via, null) { }
        public PeerMessageFilter(Uri via, EndpointAddress to)
        {
            Fx.Assert(via != null, "PeerMessageFilter via can not be set to null");
            this.via = via;
            if (to != null)
                this.actingAs = to.Uri;
        }

        public bool Match(Uri peerVia, Uri toCond)
        {
            bool result = false;
            if (peerVia == null)
            {
                result = false;
            }
            else if (Uri.Compare(this.via, peerVia,
               (UriComponents.Scheme | UriComponents.UserInfo | UriComponents.Host | UriComponents.Port | UriComponents.Path),
               UriFormat.SafeUnescaped, StringComparison.OrdinalIgnoreCase) != 0)
            {
                result = false;
            }
            else if (this.actingAs != null)
            {
                result = Uri.Compare(this.actingAs, toCond,
               (UriComponents.Scheme | UriComponents.UserInfo | UriComponents.Host | UriComponents.Port | UriComponents.Path),
               UriFormat.SafeUnescaped, StringComparison.OrdinalIgnoreCase) == 0;
            }
            else
                result = true;

            return result;
        }

    }
}


text:
require 'spec_helper'

describe 'Admin > Users > Impersonation Tokens', :js do
  let(:admin) { create(:admin) }
  let!(:user) { create(:user) }

  def active_impersonation_tokens
    find(".table.active-tokens")
  end

  def no_personal_access_tokens_message
    find(".settings-message")
  end

  def created_impersonation_token
    find("#created-personal-access-token").value
  end

  before do
    sign_in(admin)
  end

  describe "token creation" do
    it "allows creation of a token" do
      name = 'Hello World'

      visit admin_user_impersonation_tokens_path(user_id: user.username)
      fill_in "Name", with: name

      # Set date to 1st of next month
      find_field("Expires at").click
      find(".pika-next").click
      click_on "1"

      # Scopes
      check "api"
      check "read_user"

      click_on "Create impersonation token"

      expect(active_impersonation_tokens).to have_text(name)
      expect(active_impersonation_tokens).to have_text('In')
      expect(active_impersonation_tokens).to have_text('api')
      expect(active_impersonation_tokens).to have_text('read_user')
      expect(PersonalAccessTokensFinder.new(impersonation: true).execute.count).to equal(1)
      expect(created_impersonation_token).not_to be_empty
    end
  end

  describe 'active tokens' do
    let!(:impersonation_token) { create(:personal_access_token, :impersonation, user: user) }
    let!(:personal_access_token) { create(:personal_access_token, user: user) }

    it 'only shows impersonation tokens' do
      visit admin_user_impersonation_tokens_path(user_id: user.username)

      expect(active_impersonation_tokens).to have_text(impersonation_token.name)
      expect(active_impersonation_tokens).not_to have_text(personal_access_token.name)
    end
  end

  describe "inactive tokens" do
    let!(:impersonation_token) { create(:personal_access_token, :impersonation, user: user) }

    it "allows revocation of an active impersonation token" do
      visit admin_user_impersonation_tokens_path(user_id: user.username)

      accept_confirm { click_on "Revoke" }

      expect(page).to have_selector(".settings-message")
      expect(no_personal_access_tokens_message).to have_text("This user has no active Impersonation Tokens.")
    end

    it "removes expired tokens from 'active' section" do
      impersonation_token.update(expires_at: 5.days.ago)

      visit admin_user_impersonation_tokens_path(user_id: user.username)

      expect(page).to have_selector(".settings-message")
      expect(no_personal_access_tokens_message).to have_text("This user has no active Impersonation Tokens.")
    end
  end
end


text:
<?php

namespace Teacher\Classroom\Http;

use Domain\Http\Controllers\AbstractController;
use Domain\Http\Controllers\Traits\AllTrait;
use Teacher\Classroom\ClassroomRepository as Repository;

/**
 * It's don't work, because Requests and Repository don't exists.
 */
class ClassroomController extends AbstractController
{
    use AllTrait;

    protected $with = ['schedule', 'matters', 'students', 'teacher'];

    public function repo()
    {
        return Repository::class;
    }

    /**
     * Get all :item.
     *
     * @return  \Illuminate\Database\Eloquent\Collection
     */
    public function index()
    {
        return $this->repo->all($this->columns, $this->with, $this->load);
    }
}


text:
using System.Collections.Generic;

namespace CodingConnected.TraCI.NET.Types
{
    /// <summary>
    /// Please refer to  https://sumo.dlr.de/wiki/TraCI/Object_Variable_Subscription
    /// </summary>
    public class VariableSubscriptionEventArgs : SubscriptionEventArgs
    {
        public IReadOnlyDictionary<byte, IResponseInfo> ResponseByVariableCode { get; }

        public VariableSubscriptionEventArgs(
            string objectId,
            int variableCount,
            IReadOnlyDictionary<byte, IResponseInfo> responseByVariableCode) : base(objectId, variableCount)
        {
            ResponseByVariableCode = responseByVariableCode;
        }
    }
}


text:
package com.getshared.eStore.app;

import java.util.ArrayList;
import java.util.HashMap;

public class Category {

    String categoryName;
    String categoryUrl;
    String CategoryDescription;
    ArrayList<String> urlList;
    HashMap<String, ArrayList<String>> categoryList;

    public HashMap<String, ArrayList<String>> getCategoryList() {
        return categoryList;
    }

    public void setCategoryList(HashMap<String, ArrayList<String>> categoryList) {
        this.categoryList = categoryList;
    }

    public ArrayList<String> getUrlList() {
        return urlList;
    }

    public void setUrlList(ArrayList<String> urlList) {
        this.urlList = urlList;
    }

    Category(String categoryName, String categoryUrl) {
        this.categoryName = categoryName;
        this.categoryUrl = categoryUrl;
    }

    Category(String categoryName, ArrayList<String> urlList) {
        this.categoryName = categoryName;
        this.urlList = urlList;
    }

    Category(String categoryName, HashMap<String, ArrayList<String>> categoryList) {
        this.categoryName = categoryName;
        this.categoryList = categoryList;
    }

    Category(HashMap<String, ArrayList<String>> categoryList) {
        this.categoryList = categoryList;
    }

    public Category() {
    }

    public String getCategoryName() {
        return categoryName;
    }

    public void setCategoryName(String categoryName) {
        this.categoryName = categoryName;
    }

    public String getCategoryUrl() {
        return categoryUrl;
    }

    public void setCategoryUrl(String categoryUrl) {
        this.categoryUrl = categoryUrl;
    }

    public String getCategoryDescription() {
        return CategoryDescription;
    }

    public void setCategoryDescription(String categoryDescription) {
        CategoryDescription = categoryDescription;
    }

    @Override
    public String toString() {
        return "Category [categoryName=" + categoryName + ", categoryUrl="
                + categoryUrl + ", CategoryDescription=" + CategoryDescription
                + "]";
    }
}


text:
#import <Foundation/Foundation.h>

#import "MSAbstractLog.h"

/**
 * Error attachment log.
 */
@interface MSErrorAttachmentLog : MSAbstractLog

/**
 * Content type (text/plain for text).
 */
@property(nonatomic, copy) NSString *contentType;

/**
 * File name.
 */
@property(nonatomic, copy) NSString *filename;

/**
 * The attachment data.
 */
@property(nonatomic, copy) NSData *data;

/**
 * Initialize an attachment with a given filename and `NSData` object.
 *
 * @param filename The filename the attachment should get. If nil will get an automatically generated filename.
 * @param data The attachment data as `NSData`.
 * @param contentType The content type of your data as MIME type.
 *
 * @return An instance of `MSErrorAttachmentLog`.
 */
- (instancetype)initWithFilename:(NSString *)filename attachmentBinary:(NSData *)data contentType:(NSString *)contentType;

/**
 * Initialize an attachment with a given filename and text.
 *
 * @param filename The filename the attachment should get. If nil will get an automatically generated filename.
 * @param text The attachment text.
 *
 * @return An instance of `MSErrorAttachmentLog`.
 */
- (instancetype)initWithFilename:(NSString *)filename attachmentText:(NSString *)text;

@end


text:
package com.nelsonjrodrigues.pchud.net;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.concurrent.TimeUnit;

/**
 * Listens for Project Cars UDP messages on the network.
 *
 * @author nelson
 *
 */
public class NetListener implements AutoCloseable {

    private static final int MAX_PACKET_SIZE = 1367;

    private DatagramSocket socket;
    private PcMessageParser parser;

    public NetListener() throws IOException {
        this.socket = new DatagramSocket(5606);
        this.parser = new PcMessageParser();
    }

    public PcMessage listenForMessage(long timeout, TimeUnit unit) throws IOException {
        byte[] buffer = new byte[MAX_PACKET_SIZE];

        DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
        socket.setSoTimeout((int) unit.toMillis(timeout));
        socket.receive(packet);

        return parser.fromDatagramPacket(packet);
    }

    /**
     * Closes the underlying socket and interrupts a {@link NetListener#listenForMessage()} call.
     * May be called from a different thread.
     *
     */
    @Override
    public void close() {
        socket.close();
    }

}