text:
require('user_modules/script_runner').isTestApplicable({ { extendedPolicy = { "HTTP" } } })

--[[ General configuration parameters ]]
config.application1.registerAppInterfaceParams.appHMIType = { "DEFAULT" }
config.application1.registerAppInterfaceParams.isMediaApplication = false

--[[ Required Shared libraries ]]
local mobileSession = require("mobile_session")
local commonFunctions = require("user_modules/shared_testcases/commonFunctions")
local commonSteps = require("user_modules/shared_testcases/commonSteps")
local commonTestCases = require("user_modules/shared_testcases/commonTestCases")
local SDL = require("SDL")
local json = require("modules/json")

--[[ Local Variables ]]
local policy_file_path = commonFunctions:read_parameter_from_smart_device_link_ini("SystemFilesPath")
local sequence = { }
local r_actual_hmi_levels = { }
local r_actual_OnPermissionsChange = { }

--[[ Local Functions ]]
local function timestamp()
  local f = io.popen("date +%H:%M:%S.%3N")
  local o = f:read("*all")
  f:close()
  return (o:gsub("\n", ""))
end

local function log(event, ...)
  table.insert(sequence, { ts = timestamp(), e = event, p = {...} })
end

local function get_app_hmi_id(self, id)
  return self.applications["App_" .. id]
end

local function ptsToTable(pts_f)
  local f = io.open(pts_f, "r")
  local content = f:read("*all")
  f:close()
  return json.decode(content)
end

local function register_default_app(self, id)
  EXPECT_HMICALL("BasicCommunication.UpdateAppList")
  :Do(function(_, d)
      self.hmiConnection:SendResponse(d.id, d.method, "SUCCESS", { })
      self.applications = { }
      for _, app in pairs(d.params.applications) do
        self.applications[app.appName] = app.appID
      end
    end)
  local corId = self["mobileSession" .. id]:SendRPC("RegisterAppInterface", config["application" .. id].registerAppInterfaceParams)
  self["mobileSession" .. id]:ExpectResponse(corId, { success = true, resultCode = "SUCCESS" })
end

local function start_mobile_session(self, id)
  self["mobileSession" .. id] = mobileSession.MobileSession(self, self.mobileConnection)
  self["mobileSession" .. id]:StartService(7)
end

local function activate_app(self, id)
  local requestId1 = self.hmiConnection:SendRequest("SDL.ActivateApp", { appID = get_app_hmi_id(self, id) })
  EXPECT_HMIRESPONSE(requestId1)
end

local function deactivate_app(self, id)
  self.hmiConnection:SendNotification("BasicCommunication.OnAppDeactivated", { appID = get_app_hmi_id(self, id), reason = "GENERAL"})
end

local function register_OnPermissionsChange(self, id)
  self["mobileSession" .. id]:ExpectNotification("OnPermissionsChange")
  :Do(function(_, d)
      log("SDL->MOB" .. id .. ": OnPermissionsChange()", d.payload.requestType)
      r_actual_OnPermissionsChange[id] = true
    end)
  :Times(AnyNumber())
  :Pin()
end

local function updatePTU(ptu, id)
  local app_id = "000000"..id
  if ptu.policy_table.consumer_friendly_messages.messages then
    ptu.policy_table.consumer_friendly_messages.messages = nil
  end
  ptu.policy_table.device_data = nil
  ptu.policy_table.module_meta = nil
  ptu.policy_table.vehicle_data = nil
  ptu.policy_table.usage_and_error_counts = nil
  ptu.policy_table.app_policies[app_id] = { keep_context = false, steal_focus = false, priority = "NONE", default_hmi = "NONE" }
  ptu.policy_table.app_policies[app_id]["groups"] = { "Base-4", "Location-1" }
  ptu.policy_table.functional_groupings["DataConsent-2"].rpcs = json.null
  -- set specific data
  ptu.policy_table.app_policies[app_id].default_hmi = "BACKGROUND"
end

local function storePTUInFile(ptu, ptu_file_name)
  local f = io.open(ptu_file_name, "w")
  f:write(json.encode(ptu))
  f:close()
end

local function ptu(self, id)
  local ptu_file_name = os.tmpname()
  local ptu_table = ptsToTable("files/ptu.json")
  updatePTU(ptu_table, id)
  storePTUInFile(ptu_table, ptu_file_name)
  local corId = self["mobileSession"..id]:SendRPC("SystemRequest", { requestType = "HTTP", fileName = "PolicyTableUpdate" }, ptu_file_name)
  self["mobileSession"..id]:ExpectResponse(corId, { success = true, resultCode = "SUCCESS" })
  os.remove(ptu_file_name)
end

local function check_file_exists(name)
  local f = io.open(name, "r")
  if f ~= nil then
    io.close(f)
    return true
  else
    return false
  end
end

--[[ General Precondition before ATF start ]]
commonFunctions:SDLForceStop()
commonSteps:DeleteLogsFileAndPolicyTable()

--ToDo: shall be removed when issue: "ATF does not stop HB timers by closing session and connection" is fixed
config.defaultProtocolVersion = 2

--[[ General Settings for configuration ]]
Test = require("connecttest")
require("user_modules/AppTypes")

for i = 1, 2 do
  config["application" .. i].registerAppInterfaceParams.appName = "App_" .. i
end
config.application1.registerAppInterfaceParams.isMediaApplication = false
config.application1.registerAppInterfaceParams.appHMIType = { "DEFAULT" }

--[[ Preconditions ]]
commonFunctions:newTestCasesGroup("Preconditions")

function Test.Precondition_StopSDL()
  StopSDL()
end

function Test.Precondition_Clean()
  commonSteps:DeleteLogsFileAndPolicyTable()
  SDL.AppInfo.clean() -- in order to skip resumption
  os.remove(policy_file_path .. "/sdl_snapshot.json")
  if not check_file_exists(policy_file_path .. "/sdl_snapshot.json") then
    print("PTS is removed")
  end
end

function Test.Precondition_StartSDL()
  StartSDL(config.pathToSDL, config.ExitOnCrash)
end

function Test:Precondition_initHMI()
  self:initHMI()
end

function Test:Precondition_initHMI_onReady()
  self:initHMI_onReady()
end

function Test:Precondition_ConnectMobile()
  self:connectMobile()
end

function Test:StartMobileSession_1()
  start_mobile_session(self, 1)
end

function Test:StartMobileSession_2()
  start_mobile_session(self, 2)
end

-- function Test:Register_OnHMIStatus()
-- register_OnHMIStatus(self, 1)
-- register_OnHMIStatus(self, 2)
-- end

function Test:RegisterApp_1()
  register_default_app(self, 1)
  self["mobileSession1"]:ExpectNotification("OnHMIStatus",{ systemContext = "MAIN", hmiLevel = "NONE"})
  :Do(function(_, d)
      print("SDL->MOB1: OnHMIStatus()", d.payload.hmiLevel)
      r_actual_hmi_levels[1] = d.payload.hmiLevel
    end)
end

function Test:RegisterApp_2()
  register_default_app(self, 2)
  self["mobileSession2"]:ExpectNotification("OnHMIStatus",{ systemContext = "MAIN", hmiLevel = "NONE"})
  :Do(function(_, d)
      print("SDL->MOB2: OnHMIStatus()", d.payload.hmiLevel)
      r_actual_hmi_levels[2] = d.payload.hmiLevel
    end)
end

function Test:ActivateApp_1()
  activate_app(self, 1) -- app1 -> FULL
  self["mobileSession1"]:ExpectNotification("OnHMIStatus",{ systemContext = "MAIN", hmiLevel = "FULL"})
  :Do(function(_, d)
      print("SDL->MOB1: OnHMIStatus()", d.payload.hmiLevel)
      r_actual_hmi_levels[1] = d.payload.hmiLevel
    end)
end

function Test:DeactivateApp_1() -- app1 -> BACKGROUND
  deactivate_app(self, 1)
  self["mobileSession1"]:ExpectNotification("OnHMIStatus",{ systemContext = "MAIN", hmiLevel = "BACKGROUND"})
  :Do(function(_, d)
      print("SDL->MOB1: OnHMIStatus()", d.payload.hmiLevel)
      r_actual_hmi_levels[1] = d.payload.hmiLevel
    end)
end

function Test.ShowHMILevels()
  if r_actual_hmi_levels[1] == nil then
    r_actual_hmi_levels[1] = "NONE"
  end
  print("--- HMILevels (app: level) -----------------------")
  for k, v in pairs(r_actual_hmi_levels) do
    print(k .. ": " .. v)
  end
  print("--------------------------------------------------")
end

function Test:Register_OnPermissionsChange()
  register_OnPermissionsChange(self, 1)
  register_OnPermissionsChange(self, 2)
end

--[[ Test ]]
commonFunctions:newTestCasesGroup("Test")

function Test:Test_PTU_1()
  ptu(self, 1)
  self["mobileSession1"]:ExpectNotification("OnHMIStatus"):Times(0)
  self["mobileSession2"]:ExpectNotification("OnHMIStatus"):Times(0)
  commonTestCases:DelayedExp(10000)
end

function Test:Test_UPDATING()
  local reqId = self.hmiConnection:SendRequest("SDL.GetStatusUpdate")
  EXPECT_HMIRESPONSE(reqId, {status = "UPDATING"})
end

function Test:Test_PTU_2()
  self.hmiConnection:SendNotification("BasicCommunication.OnSystemRequest", { requestType = "HTTP", fileName = "PolicyTableUpdate", appID = self.applications["App_2"] })
  self.mobileSession2:ExpectNotification("OnSystemRequest", { requestType = "HTTP" })
  :Do(function()
    ptu(self, 2)
  end)
  self["mobileSession1"]:ExpectNotification("OnHMIStatus"):Times(0)
  self["mobileSession2"]:ExpectNotification("OnHMIStatus"):Times(0)
  commonTestCases:DelayedExp(10000)
end

function Test:Test_UP_TO_DATE()
  local reqId = self.hmiConnection:SendRequest("SDL.GetStatusUpdate")
  EXPECT_HMIRESPONSE(reqId, {status = "UP_TO_DATE"})
end

function Test.Test_ShowSequence()
  print("--- Sequence -------------------------------------")
  for k, v in pairs(sequence) do
    local s = k .. ": " .. v.ts .. ": " .. v.e
    for _, val in pairs(v.p) do
      if val then s = s .. ": " .. val end
    end
    print(s)
  end
  print("--------------------------------------------------")
end

function Test:Test_Validation_OnHMIStatus()
  local r_expected_hmi_levels = { "BACKGROUND", "NONE" }
  for i = 1, 2 do
    if r_expected_hmi_levels[i] ~= r_actual_hmi_levels[i] then
      local msg = table.concat({
          "\nExpected OnHMIStatus() level for app '", i, "' is '", r_expected_hmi_levels[i],
          "', but actual is '", r_actual_hmi_levels[i], "'"})
      self:FailTestCase(msg)
    end
  end
end

function Test:Test_Validation_OnPermissionsChange()
  local r_expected_OnPermissionsChange = { true, true }
  for i = 1, 2 do
    if r_expected_OnPermissionsChange[i] ~= r_actual_OnPermissionsChange[i] then
      local msg = table.concat({"\nExpected OnPermissionsChange() notification for app '", i, "' was not sent"})
      self:FailTestCase(msg)
    end
  end
end

--[[ Postconditions ]]
commonFunctions:newTestCasesGroup("Postconditions")

function Test.Postconditions_StopSDL()
  StopSDL()
end

return Test


text:
<?php
/**
 ++++++++++++++++++++++++++++++++++++
 *  -> 开发规范管理
 ++++++++++++++++++++++++++++++++++++
 */
namespace modules\develop_info;

include_once(BASE_PATH.'Michelf/MarkdownExtra.inc.php');
use \Michelf\MarkdownExtra;

defined('_ACCESS_GRANT') or exit('没有访问权限!');

class develop_doc extends \common\libs\classes\Base{
    public function __construct(){
        parent::__construct();
    }

    /** markdown格式接口 */
    public function develop_public(){
        $gData = checkData($_GET);
        $int_opt = $gData['int_opt'];

        if(!$int_opt)
            ajaxReturn('非法操作[缺少必须参数]',300);

        //样式
        echo '<style>
            .markdown-here-wrapper h1{ font-size: 20px; font-weight:bold; margin-top: 10px;}
            .markdown-here-wrapper h2{ font-size: 18px; font-weight:bold; margin-top: 10px;}
            .markdown-here-wrapper h3{ font-size: 16px; font-weight:bold; margin-top: 10px;}
            .markdown-here-wrapper table{ border-collapse: collapse; border: 1px solid yellowgreen;}
            .markdown-here-wrapper th { vertical-align: baseline; border: 1px solid yellowgreen; font-weight:bold; font-size: 18px;}
            .markdown-here-wrapper td { vertical-align: middle; border: 1px solid yellowgreen; font-size: 18px;}
            .markdown-here-wrapper tr { border: 1px solid yellowgreen;}

            .markdown-here-wrapper p a{font-size: 16px;}
            </style>';

        $output = $text = file_get_contents(MODULE_PATH.'develop_info/'.$int_opt.'.md');
        $parser = new MarkdownExtra;
        $my_html = $parser->transform($output);

        $this->s->assign('my_html',$my_html);
        $this->s->display('interface_admin/interface_list.html');
    }

}

redpajama_set_name: RedPajamaGithub


text:
class Renderer : public ndnrtc::IExternalRenderer {
public:
    Renderer(const std::string& pipeName);
    ~Renderer();

private:
    Renderer(const Renderer&) = delete;
    int pipe_, width_, height_;
    size_t bufferSize_;
    uint8_t *buffer_;
    std::string pipePath_;

    void createPipe(const std::string&);
    void openPipe(const std::string&);

    uint8_t* getFrameBuffer(int width, int height, IExternalRenderer::BufferType*) override;
    void renderFrame(const ndnrtc::FrameInfo&, int width, int height,
                     const uint8_t* buffer) override;
};

#endif


text:
"""fragments are block of html which can be dynamically added"""

from django.contrib.auth.decorators import login_required
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import PermissionDenied
from django.forms.models import modelformset_factory
from django.shortcuts import render
from django.utils.translation import ugettext as _

from colorbox.decorators import popup_close

from coop_cms.forms.fragments import AddFragmentForm, EditFragmentForm
from coop_cms import models

@login_required
@popup_close
def add_fragment(request):
    """add a fragment to the current template"""

    content_type = ContentType.objects.get_for_model(models.Fragment)
    perm = '{0}.add_{1}'.format(content_type.app_label, content_type.model)
    if not request.user.has_perm(perm):
        raise PermissionDenied

    if request.method == "POST":
        form = AddFragmentForm(request.POST)
        if form.is_valid():
            form.save()
            # popup_close decorator will close and refresh
            return None
    else:
        form = AddFragmentForm()

    context_dict = {
        'form': form,
    }

    return render(
        request,
        'coop_cms/popup_add_fragment.html',
        context_dict
    )

@login_required
@popup_close
def edit_fragments(request):
    """edit fragments of the current template"""

    content_type = ContentType.objects.get_for_model(models.Fragment)
    perm = '{0}.add_{1}'.format(content_type.app_label, content_type.model)
    if not request.user.has_perm(perm):
        raise PermissionDenied

    edit_fragment_formset = modelformset_factory(models.Fragment, EditFragmentForm, extra=0)

    if request.method == "POST":
        formset = edit_fragment_formset(request.POST, queryset=models.Fragment.objects.all())
        if formset.is_valid():
            formset.save()
            # popup_close decorator will close and refresh
            return None
    else:
        formset = edit_fragment_formset(queryset=models.Fragment.objects.all())

    context_dict = {
        'form': formset,
        'title': _("Edit fragments of this template?"),
    }

    return render(
        request,
        'coop_cms/popup_edit_fragments.html',
        context_dict
    )


text:
/**
 * Different graph representations that can be used in DataSets.
 */
package org.gradoop.flink.representation;


text:
TIME_RUN_DEVOPS=$(date +%s)

echo "##########################################################"
echo "####          Install and setup DevOps tools v1       ####"
echo "##########################################################"

export DEBIAN_FRONTEND=noninteractive

echo "==> Installing Git, awscli, curl, jq, unzip and software-properties-common (apt-add-repository)"
sudo apt update
sudo apt install -y git awscli curl jq unzip software-properties-common sudo apt-transport-https
printf ">> Git, awscli, curl, jq and unzip installed. \n\n"

# Disabled installation of Ansible (Ubuntu 20.04 has issues)
#echo "==> Installing Ansible"
#sudo apt-add-repository --yes --update ppa:ansible/ansible
#sudo apt install -y ansible
#printf ">> Ansible installed.\n\n"

echo "==> Installing Java 8, 11 (default) and Oracle Java 11"
sudo apt install -y default-jdk openjdk-8-jdk
##sudo add-apt-repository --yes --update ppa:linuxuprising/java
##sudo apt install -y oracle-java11-installer-local
printf ">> Java installed.\n\n"

echo "==> Selecting Java/Javac 8 as default version and auto-mode"
sudo update-alternatives --install /usr/bin/java java /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java 1200
sudo update-alternatives --install /usr/bin/javac javac /usr/lib/jvm/java-8-openjdk-amd64/bin/javac 1200
printf "\n\n"

echo "==> Installing Maven"
sudo apt install -y maven
printf ">> Maven installed.\n\n"

echo "==> Creating '/etc/profile.d/maven.sh'"
cat << 'EOF' > maven.sh
#!/bin/bash

JAVA_HOME=/usr/lib/jvm/default-java
M2_HOME=/opt/maven
MAVEN_HOME=/opt/maven
## removed 'export' and replaced '${xyz}' for '$xyz'
PATH=$M2_HOME/bin:$PATH
EOF
sudo chown -R root:root maven.sh
sudo chmod +x maven.sh
sudo mv maven.sh /etc/profile.d/maven.sh
. /etc/profile.d/maven.sh
printf ">> Java and Maven configured."
mvn -version
printf "\n\n"

echo "==> Installing VS Code"
wget -q https://raw.githubusercontent.com/chilcano/how-tos/master/src/vscode_install.sh
chmod +x vscode_install.sh
. vscode_install.sh
rm -f vscode_install.sh
printf ">> VS Code installed.\n\n"

echo "==> Configuring VS Code and installing Extensions"
wget -q https://raw.githubusercontent.com/chilcano/how-tos/master/src/vscode_setup.sh
chmod +x vscode_setup.sh
. vscode_setup.sh
rm -f vscode_setup.sh
printf ">> VS Code config and extensions installed.\n\n"

echo "==> Installing Terraform"
TF_VERSION="0.11.15-oci"
TF_VERSION_LATEST=$(curl -s https://checkpoint-api.hashicorp.com/v1/check/terraform | jq -r -M '.current_version')
TF_VERSION="${TF_VERSION:-$TF_VERSION_LATEST}"
TF_BUNDLE="terraform_${TF_VERSION}_linux_amd64.zip"
wget --quiet "https://releases.hashicorp.com/terraform/${TF_VERSION}/${TF_BUNDLE}"
unzip "${TF_BUNDLE}"
sudo mv terraform /usr/local/bin/
rm -rf terraf*
printf ">> Terraform ${TF_VERSION} installed.\n\n"

echo "==> Installing Packer"
PACKER_VERSION="1.5.5"
PACKER_VERSION_LATEST=$(curl -s https://checkpoint-api.hashicorp.com/v1/check/packer | jq -r -M '.current_version')
PACKER_VERSION="${PACKER_VERSION:-$PACKER_VERSION_LATEST}"
PACKER_BUNDLE="packer_${PACKER_VERSION}_linux_amd64.zip"
wget --quiet "https://releases.hashicorp.com/packer/${PACKER_VERSION}/${PACKER_BUNDLE}"
unzip "${PACKER_BUNDLE}"
sudo mv packer /usr/local/bin/
rm -rf packer*
printf ">> Packer installed.\n\n"

printf "==> Installing Chromium \n"
sudo apt install -yq chromium-browser
printf ">> Chromium installed.\n\n"

printf ">> Duration: $((($(date +%s)-${TIME_RUN_DEVOPS}))) seconds.\n\n"


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, maximum-scale=1">
    <title>{% block title %}{{ _('Mozilla Add-ons') }}{% endblock %}</title>

    <link rel="shortcut icon" type="image/x-icon"
          href="{{ media('img/favicon.ico') }}">

    {% block rss_feed %}{% endblock %}

    {# L10n: {0} is an application, like Firefox. #}
    <link title="{{ _('{0} Add-ons')|f(APP.pretty) }}"
          rel="search" type="application/opensearchdescription+xml"
          href="{{ url('amo.opensearch') }}" />

    {% block site_css %}
      {{ css('zamboni/mobile') }}
    {% endblock %}

    {% if settings.DEBUG %}
      {{ js('debug') }}
      {% if settings.REMOTE_JS_DEBUG %}
        <meta id="remote_debug_server" name="remote_debug_server" value="{{ settings.REMOTE_JS_DEBUG }}">

      {% endif %}
    {% endif %}

    {% block extrahead %}{% endblock %}

  <body class="html-{{ DIR }} {{ request.APP.short }} lang-{{ LANG }} {% block bodyclass %}{% endblock %}"
        data-app="{{ request.APP.short }}"
        data-appname="{{ request.APP.pretty }}"
        data-appid="{{ request.APP.id }}"
        data-min-beta-version="{{ settings.MIN_BETA_VERSION }}"
        data-anonymous="{{ (not request.user.is_authenticated())|json }}"
        data-readonly="{{ settings.READ_ONLY|json }}"
        data-media-url="{{ MEDIA_URL }}"
        {% if request.ALLOWS_PJAX %}
          data-use-pjax="1"
          data-pjax-container="{{ settings.PJAX_SELECTOR }}"
        {% endif %}
        {% block bodyattrs %}{% endblock %}>

      {% block header %}

          {% include "mobile/header.html" %}
          <hgroup>

              {% set appicon = 'firefox' if request.APP == amo.MOBILE else request.APP.short %}

                {{ _('Mobile Add-ons') }}

          </hgroup>

            {{ _('You need Firefox to install add-ons. Learn More »') }}

          {% block back_link %}

            <svg width="18" height="16"><polygon fill="#447BC4" points="9,0 18,9 15,9 15,16 11,16 11,11 7,11 7,18 3,16 3,9 0,9"/></svg>
            {{ _('Mobile Add-ons Home') }}
          {% endblock %}

      {% endblock %}

        {% block page %}
        {% endblock page %}

        {% include "includes/lang_switcher.html" %}
        {% block footer %}
          {{ _('View full site') }}

            {{ _('Privacy Policy') }}  |
            {{ _('Legal Notices') }}

        {% endblock footer %}

    {% block staging %}
    {% endblock %}
    {# js #}
    {% block site_js %}

      {{ js('zamboni/mobile') }}
    {% endblock %}
    {% block js %}{% endblock %}
    {# Webtrends Stats Tracking #}

    {# End Webtrends #}


text:
package com.example.achuan.teammanagement.ui.main.activity;

import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import com.example.achuan.teammanagement.R;
import com.example.achuan.teammanagement.app.Constants;
import com.example.achuan.teammanagement.base.SimpleActivity;
import com.example.achuan.teammanagement.model.db.ContactUser;
import com.example.achuan.teammanagement.model.db.LitePalDBHelper;
import com.example.achuan.teammanagement.model.db.InviteMessage;
import com.example.achuan.teammanagement.model.http.EaseMobHelper;
import com.example.achuan.teammanagement.ui.contacts.fragment.ContactsMainFragment;
import com.example.achuan.teammanagement.ui.conversation.fragment.ConversationMainFragment;
import com.example.achuan.teammanagement.ui.explore.fragment.ExploreMainFragment;
import com.example.achuan.teammanagement.ui.myself.fragment.MyselfMainFragment;
import com.example.achuan.teammanagement.util.DialogUtil;
import com.example.achuan.teammanagement.util.SharedPreferenceUtil;
import com.example.achuan.teammanagement.util.StringUtil;
import com.example.achuan.teammanagement.util.SystemUtil;
import com.hyphenate.EMCallBack;
import com.hyphenate.EMConnectionListener;
import com.hyphenate.EMContactListener;
import com.hyphenate.EMError;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.util.EMLog;

import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

public class MainActivity extends SimpleActivity implements BottomNavigationView.OnNavigationItemSelectedListener {

    public static final String TAG="MainActivity";

    //需要装载到主活动中的Fragment的引用变量
    ConversationMainFragment mNewsMainFragment;
    ContactsMainFragment mContactsMainFragment;
    ExploreMainFragment mExploreMainFragment;
    MyselfMainFragment mMyselfMainFragment;

    //定义变量记录需要隐藏和显示的fragment的编号
    private int hideFragment = Constants.TYPE_NEWS;
    private int showFragment = Constants.TYPE_NEWS;

    //记录左侧navigation的item点击
    MenuItem mLastMenuItem;//历史
    int contentViewId;//内容显示区域的控件的id号,后面用来添加碎片使用

    @BindView(R.id.btm_nav)
    BottomNavigationView mBtmNav;
    @BindView(R.id.toolbar)
    Toolbar mToolbar;

    EMContactListener mEMContactListener;//联系人监听
    EMMessageListener mEMMessageListener;//消息监听
    EMConnectionListener mEMConnectionListener;//用户连接监听

    @Override
    protected int getLayout() {
        return R.layout.activity_main;
    }

    @Override
    protected void initEventAndData() {
        /********************检测并打开网络****************/
        //SystemUtil.checkAndShowNetSettingDialog(this);
        contentViewId = R.id.fl_main_content;//获取内容容器的ID号

        /***1-初始化底部导航栏设置***/
        //初始化第一次显示的item为设置界面
        mLastMenuItem = mBtmNav.getMenu().findItem(R.id.bottom_0);
        mLastMenuItem.setChecked(true);
        //添加点击监听事件
        mBtmNav.setOnNavigationItemSelectedListener(this);

        /***2-初始化创建模块的fragment实例对象,并装载到主布局中****/
        //初始化toolbar
        setToolBar(mToolbar, (String) mLastMenuItem.getTitle(),false);
        //mToolbar.setLogo(R.drawable.logo);//设置logo
        //先添加这两个碎片
        mNewsMainFragment = new ConversationMainFragment();
        mContactsMainFragment = new ContactsMainFragment();
        addFragment(contentViewId,mContactsMainFragment);
        addFragment(contentViewId,mNewsMainFragment);
        //默认先显示会话界面
        showFragment(mContactsMainFragment, mNewsMainFragment);
        //并将第一界面碎片添加到布局容器中
        //replaceFragment(contentViewId, getTargetFragment(showFragment));
        SharedPreferenceUtil.setCurrentItem(showFragment);

        /**1.1-注册联系人变动监听***/
        mEMContactListener=new MyContactListener();
        mEMMessageListener=new MyMessageListener();
        EMClient.getInstance().contactManager().setContactListener(mEMContactListener);

        /**4.2-注册用户登录监听*/
        mEMConnectionListener=new MyConnectionListener();
        EMClient.getInstance().addConnectionListener(mEMConnectionListener);

    }

    /**4.4-用户登录异常时,强制下线处理*/
    private void forcedOfflineDeal(){

        DialogUtil.createOneButtonDialog(this, "下线通知",
                "同一账号已在其它设备登录", "确定", false, new DialogUtil.OnOneButtonDialogClickListener() {
                    @Override
                    public void onClick() {
                                /*---执行登出操作---*/
                        EaseMobHelper.getInstance().logout(false,new EMCallBack() {
                            @Override
                            public void onSuccess() {
                                runOnUiThread(new Runnable() {
                                    public void run() {
                                        //后期可以设置是否退出后清空当前用户的缓存数据,即删除数据库文件
                                        //结束主界面并跳转到登录页面
                                        startActivity(new Intent(MainActivity.this, LoginActivity.class));
                                        finish();
                                    }
                                });
                            }
                            @Override
                            public void onProgress(int progress, String status) {
                            }
                            @Override
                            public void onError(int code, String message) {
                                //需要在主线程中进行UI更新
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        // TODO Auto-generated method stub
                                        Toast.makeText(MainActivity.this,
                                                "unbind devicetokens failed",
                                                Toast.LENGTH_SHORT)
                                                .show();
                                    }
                                });
                            }
                        });
                    }
                });
    }

    /**4.3-用户登录异常后,提醒异常消息(强制下线),然后跳转到登录界面*/
    protected void onUserException(String exception){
        //EMLog.e(TAG, "onUserException: " + exception);
        switch (exception){
            case Constants.ACCOUNT_REMOVED:
                break;
            case Constants.ACCOUNT_CONFLICT:
                forcedOfflineDeal();
                break;
            case Constants.ACCOUNT_FORBIDDEN:
                break;
            default:break;
        }
    }

    /**4.1-自定义用户连接监听器类*/
    public class MyConnectionListener implements EMConnectionListener{
        @Override
        public void onConnected() {

        }
        @Override
        public void onDisconnected(final int errorCode) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    EMLog.d("global listener", "onDisconnect" + errorCode);
                    if (errorCode == EMError.USER_REMOVED) {
                        onUserException(Constants.ACCOUNT_REMOVED);
                    } else if (errorCode == EMError.USER_LOGIN_ANOTHER_DEVICE) {
                        onUserException(Constants.ACCOUNT_CONFLICT);
                            /*Toast.makeText(MainActivity.this,
                                    "同一账号已在异地登录",
                                    Toast.LENGTH_SHORT).show();*/
                    } else if (errorCode == EMError.SERVER_SERVICE_RESTRICTED) {
                        onUserException(Constants.ACCOUNT_FORBIDDEN);
                    }
                }
            });
        }
    }

    /**3.3-收到消息时刷新会话列表显示*/
    private void refreshConversationWithMessage() {
        runOnUiThread(new Runnable() {
            public void run() {
                //更新显示未读消息数
                //updateUnreadLabel();
                //if (mBtmNav== 0) 如果当前处于会话界面,才进行会话界面实时更新
                if(mNewsMainFragment!=null){
                    //刷新会话列表显示
                    mNewsMainFragment.refresh();
                }
            }
        });
    }

    /**3.2-活动不再可见时移除监听*/
    @Override
    protected void onStop() {
        super.onStop();
        EMClient.getInstance().chatManager().removeMessageListener(mEMMessageListener);
    }

    /**3.1-恢复交互时重新添加监听*/
    @Override
    protected void onResume() {
        super.onResume();
        EMClient.getInstance().chatManager().addMessageListener(mEMMessageListener);
    }

    /**3.0-自定义消息listener类
     * 在onResume()中添加,onStop()中移除
     * */
    public class MyMessageListener implements EMMessageListener{
        //收到消息
        @Override
        public void onMessageReceived(List<EMMessage> messages) {
            refreshConversationWithMessage();
        }
        //收到透传消息
        @Override
        public void onCmdMessageReceived(List<EMMessage> messages) {

        }
        //收到已读回执
        @Override
        public void onMessageRead(List<EMMessage> messages) {

        }
        //收到已送达回执
        @Override
        public void onMessageDelivered(List<EMMessage> messages) {

        }
        //消息状态变动
        @Override
        public void onMessageChanged(EMMessage message, Object change) {

        }
    }

    /**2-保存并提示消息的邀请消息
     * @param msg
     * */
    private void notifyNewIviteMessage(InviteMessage msg){
        /*if(inviteMessgeDao == null){
            inviteMessgeDao = new InviteMessgeDao(MainActivity.this);
        }
        inviteMessgeDao.saveMessage(msg);
        //保存未读数,这里没有精确计算
        inviteMessgeDao.saveUnreadMessageCount(1);
        // 提示有新消息
        //响铃或其他操作*/
        LitePalDBHelper.getInstance().saveMessage(msg);

    }

    /**1.2-在活动销毁时移除联系人监听器*/
    @Override
    protected void onDestroy() {
        super.onDestroy();
        EMClient.getInstance().contactManager().removeContactListener(mEMContactListener);
        EMClient.getInstance().removeConnectionListener(mEMConnectionListener);
    }

    /**1.0-自定义好友变化listener类
     * 在onCreate()中添加,onDestroy()中移除
     * */
    public class MyContactListener implements EMContactListener{
        @Override
        public void onContactAdded(final String username) {
            //增加了联系人时回调此方法
            /*---保存增加的联系人---*/
            //获取本地联系人数据
            Map<String, ContactUser> localUsers = LitePalDBHelper.getInstance().getContactList();
            // 添加好友时可能会回调added方法两次
            if (!localUsers.containsKey(username)) {
                //创建实例对象
                ContactUser user = new ContactUser();
                user.setUserName(username);
                user.setInitialLetter(StringUtil.getHeadChar(username));
                //进行查询操作,避免重复添加
                LitePalDBHelper.getInstance().saveContact(user);
            }
            runOnUiThread(new Runnable(){
                @Override
                public void run() {
                    mContactsMainFragment.refresh();//刷新通讯录界面显示
                    Toast.makeText(getApplicationContext(),
                            "增加联系人:+"+username,
                            Toast.LENGTH_SHORT).show();
                }
            });
        }
        @Override
        public void onContactDeleted(final String username) {
            //被删除时回调此方法
            //获取本地联系人数据
            Map<String, ContactUser> localUsers = LitePalDBHelper.getInstance().getContactList();
            // 本地包含此用户才执行删除操作
            if (localUsers.containsKey(username)) {
                //从本地数据库中删除
                LitePalDBHelper.getInstance().deleteContact(username);
                LitePalDBHelper.getInstance().deleteMessage(username);
            }
            runOnUiThread(new Runnable(){
                @Override
                public void run() {
                    mContactsMainFragment.refresh();//刷新通讯录界面显示
                    Toast.makeText(getApplicationContext(), "删除联系人:+"+username, Toast.LENGTH_SHORT).show();
                }
            });
        }
        //收到邀请
        @Override
        public void onContactInvited(final String username, String reason) {
            // 接到邀请的消息,如果不处理(同意或拒绝),掉线后,服务器会自动再发过来,所以客户端不需要重复提醒
            List<InviteMessage> msgs = LitePalDBHelper.getInstance().getMessagesList();

            for (InviteMessage inviteMessage : msgs) {
                //如果之前发的消息不是群邀请(好友邀请)且发起人名和当前发起人名相同,就把历史消息删除掉
                /*当前是无群聊的情况,后面引入群聊后还需进行大量优化*/
                if (inviteMessage.getGroupId() == null &&
                        inviteMessage.getFrom().equals(username)) {
                    LitePalDBHelper.getInstance().deleteMessage(username);
                }
            }

            //自己封装的javabean
            InviteMessage msg = new InviteMessage();
            msg.setFrom(username);
            msg.setTime(System.currentTimeMillis());

            /**-在消息源头进行特殊处理,提升用户体验*/
            if(reason ==null|| TextUtils.isEmpty(reason)){
                //请求加你为好友(默认显示的加好友理由)
                reason=getString(R.string.Request_to_add_you_as_a_friend);
            }

            msg.setReason(reason);
            // 设置相应status对应的序数
            msg.setStatusOrdinal(InviteMessage.InviteMesageStatus.BEINVITEED.ordinal());
            notifyNewIviteMessage(msg);

            runOnUiThread(new Runnable(){
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(), "收到好友申请:+"+username,
                            Toast.LENGTH_SHORT).show();
                }
            });
        }
        //好友请求被同意
        @Override
        public void onFriendRequestAccepted(final String username) {
            List<InviteMessage> msgs = LitePalDBHelper.getInstance().getMessagesList();

            /***---注意:下面的逻辑有待改善!!!-***/
            for (InviteMessage inviteMessage : msgs) {
                if (inviteMessage.getFrom().equals(username)) {
                    return;
                }
            }

            // 自己封装的javabean
            InviteMessage msg = new InviteMessage();
            msg.setFrom(username);
            msg.setTime(System.currentTimeMillis());
            msg.setStatusOrdinal(InviteMessage.InviteMesageStatus.BEAGREED.ordinal());
            //存储同意的消息
            notifyNewIviteMessage(msg);
            runOnUiThread(new Runnable(){
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(),
                            username+":同意了你的加好友请求", Toast.LENGTH_SHORT).show();
                }
            });
        }
        //好友请求被拒绝
        @Override
        public void onFriendRequestDeclined(final String username) {
            List<InviteMessage> msgs = LitePalDBHelper.getInstance().getMessagesList();

            /***---注意:下面的逻辑有待改善!!!-***/
            for (InviteMessage inviteMessage : msgs) {
                if (inviteMessage.getFrom().equals(username)) {
                    return;
                }
            }

            // 自己封装的javabean
            InviteMessage msg = new InviteMessage();
            msg.setFrom(username);
            msg.setTime(System.currentTimeMillis());
            msg.setStatusOrdinal(InviteMessage.InviteMesageStatus.BEREFUSED.ordinal());
            //存储同意的消息
            notifyNewIviteMessage(msg);
            runOnUiThread(new Runnable(){
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(),
                            username+":拒绝了你的加好友请求", Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    //重写back按钮的点击事件
    @Override
    public void onBackPressed() {
        SystemUtil.showExitDialog(this);
    }

    /*-----为工具栏创建菜单选项按钮-----*/
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().//获得MenuInflater对象
                inflate(R.menu.menu_toolbar_main,//指定通过哪一个资源文件来创建菜单
                menu);
        return true;//返回true,表示允许创建的菜单显示出来
    }

    /*-----为菜单按钮添加点击监听事件-----*/
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case R.id.search:
                break;
            case R.id.add_person:
                Intent intent=new Intent(this,AddContactActivity.class);
                startActivity(intent);
                Toast.makeText(this, "添加朋友", Toast.LENGTH_SHORT).show();
                break;
            default:break;
        }
        return true;//返回true,表示允许item点击响应
    }

    /*底部导航栏的切换监听事件*/
    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.bottom_0:
                showFragment = Constants.TYPE_NEWS;
                //第一次加载显示时,才创建碎片对象,并添加到内容容器中
                /*if (mNewsMainFragment == null) {
                    mNewsMainFragment = new ConversationMainFragment();
                    addFragment(contentViewId, mNewsMainFragment);
                }*/
                break;
            case R.id.bottom_1:
                showFragment = Constants.TYPE_CONTACTS;
                /*if (mContactsMainFragment == null) {
                    mContactsMainFragment = new ContactsMainFragment();
                    addFragment(contentViewId, mContactsMainFragment);
                }*/
                break;
            case R.id.bottom_2:
                showFragment = Constants.TYPE_EXPLORE;
                if (mExploreMainFragment == null) {
                    mExploreMainFragment = new ExploreMainFragment();
                    addFragment(contentViewId, mExploreMainFragment);
                }
                break;
            case R.id.bottom_3:
                showFragment = Constants.TYPE_MYSELF;
                if (mMyselfMainFragment == null) {
                    mMyselfMainFragment = new MyselfMainFragment();
                    addFragment(contentViewId, mMyselfMainFragment);
                }
                break;
            default:
                break;
        }
        /***点击item后进行显示切换处理,并记录在本地中***/
        if (mLastMenuItem != null && mLastMenuItem != item) {
            mToolbar.setTitle(item.getTitle());//改变标题栏的内容
            mLastMenuItem.setChecked(false);//取消历史选择
            item.setChecked(true);//设置当前item选择
            //记录当前显示的item
            SharedPreferenceUtil.setCurrentItem(showFragment);
            //实现fragment的切换显示
            showFragment(getTargetFragment(hideFragment), getTargetFragment(showFragment));
            //选择过的item变成了历史
            mLastMenuItem = item;
            //当前fragment显示完就成为历史了
            hideFragment = showFragment;
        }
        return true;
    }

    //根据item编号获取fragment对象的方法
    private Fragment getTargetFragment(int item) {
        switch (item) {
            case Constants.TYPE_NEWS:
                return mNewsMainFragment;
            case Constants.TYPE_CONTACTS:
                return mContactsMainFragment;
            case Constants.TYPE_EXPLORE:
                return mExploreMainFragment;
            case Constants.TYPE_MYSELF:
                return mMyselfMainFragment;
            default:
                break;
        }
        return mNewsMainFragment;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}


text:
package io.reactivex.netty.protocol.http.server;

import io.netty.bootstrap.ServerBootstrap;
import io.reactivex.netty.pipeline.PipelineConfigurators;
import io.reactivex.netty.server.AbstractServerBuilder;

/**
 * A convenience builder to create instances of {@link HttpServer}
 *
 * @author Nitesh Kant
 */
public class HttpServerBuilder<I, O> extends AbstractServerBuilder<HttpServerRequest<I>, HttpServerResponse<O>,
        HttpServerBuilder<I, O>, HttpServer<I, O>> {

    public HttpServerBuilder(int port, RequestHandler<I, O> requestHandler) {
        super(port, new HttpConnectionHandler<I, O>(requestHandler));
        pipelineConfigurator(PipelineConfigurators.<I, O>httpServerConfigurator());
    }

    public HttpServerBuilder(ServerBootstrap bootstrap, int port, RequestHandler<I, O> requestHandler) {
        super(port, new HttpConnectionHandler<I, O>(requestHandler), bootstrap);
        pipelineConfigurator(PipelineConfigurators.<I, O>httpServerConfigurator());
    }

    @Override
    protected HttpServer<I, O> createServer() {
        return new HttpServer<I, O>(serverBootstrap, port, pipelineConfigurator,
                                    (HttpConnectionHandler<I, O>) connectionHandler);
    }
}


text:
export const CLICK = 'click';
export const TOUCHSTART = 'touchstart';
export const TOUCHEND = 'touchend';
export const MOUSEOVER = 'mouseover';
export const MOUSEOUT = 'mouseout';

// Chart Support
export const SUPPRESSED_ERROR = 'suppressedError';
export const EXTENSION = 'extension';

// Chart and Extension Lifecycle (extensions support a subset)
export const BEFORE_RENDER = 'beforeRender';
export const RENDERED = 'rendered';
export const BEFORE_UPDATE = 'beforeUpdate';
export const UPDATED = 'updated';
export const BEFORE_BOUNDS_UPDATE = 'beforeBoundsUpdate';
export const BOUNDS_UPDATED = 'boundsUpdated';
export const BEFORE_CLEAR = 'beforeClear';
export const CLEARED = 'cleared';
export const BEFORE_DESTROY = 'beforeDestroy';
export const DESTROYED = 'destroyed';

export const BEFORE_OPTION_CHANGE = 'beforeOptionChange';
export const OPTION_CHANGED = 'optionChanged';
export const BEFORE_STYLE_DOMAINS_RESET = 'beforeStyleDomainsReset';
export const STYLE_DOMAINS_RESET = 'styleDomainsReset';

export const INTERACTION_EVENTS = [CLICK, TOUCHSTART, TOUCHEND, MOUSEOVER, MOUSEOUT];
export const INTERACTION_SHOW_EVENTS = [TOUCHSTART, MOUSEOVER];
export const INTERACTION_HIDE_EVENTS = [TOUCHEND, MOUSEOUT];

// Support events
export const CHART_SUPPORT_EVENTS = [SUPPRESSED_ERROR, EXTENSION];

// Lifecycle event pairs
export const CHART_LIFECYCLE_EVENTS = [
  BEFORE_RENDER, RENDERED,
  BEFORE_UPDATE, UPDATED,
  BEFORE_BOUNDS_UPDATE, BOUNDS_UPDATED,
  BEFORE_CLEAR, CLEARED,
  BEFORE_STYLE_DOMAINS_RESET, STYLE_DOMAINS_RESET,
  BEFORE_OPTION_CHANGE, OPTION_CHANGED,
  BEFORE_DESTROY, DESTROYED,
];

export const EXTENSION_LIFECYCLE_EVENTS = [
  BEFORE_UPDATE, UPDATED,
  BEFORE_CLEAR, CLEARED,
  BEFORE_OPTION_CHANGE, OPTION_CHANGED,
  BEFORE_DESTROY, DESTROYED,
];

export const ACTION_ADD = 'add';
export const ACTION_REMOVE = 'remove';
export const ACTION_CSS_OVER = 'over';
export const ACTION_CSS_TOUCH = 'touch';

export const INTERACTION_EVENT_CSS_MAP = {
  [MOUSEOVER]: { action: ACTION_ADD, css: ACTION_CSS_OVER },
  [MOUSEOUT]: { action: ACTION_REMOVE, css: ACTION_CSS_OVER },
  [TOUCHSTART]: { action: ACTION_ADD, css: ACTION_CSS_TOUCH },
  [TOUCHEND]: { action: ACTION_REMOVE, css: ACTION_CSS_TOUCH },
};


text:
import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { PlayerDetailComponent } from './player-detail.component';

describe('PlayerDetailComponentComponent', () => {
  let component: PlayerDetailComponent;
  let fixture: ComponentFixture<PlayerDetailComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ PlayerDetailComponent ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(PlayerDetailComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});


text:
package ru.furry.furview2.system;

import ru.furry.furview2.drivers.Driver;
import ru.furry.furview2.images.RemoteFurImage;

public interface ListlikeIterator<T> {
    void init(Driver driver, String searchQuery);
    void asyncLoad(AsyncHandlerUI<Boolean> remoteImagesHandler);
    boolean hasPrevious();
    T next();
    T previous();
}


text:
<?xml version="1.0" encoding="UTF-8" ?>

<ldml>
	<identity>
		<version number="$Revision: 4765 $"/>
		<generation date="$Date: 2010-02-27 18:03:30 -0600 (Sat, 27 Feb 2010) $"/>
		<language type="zu"/>
	</identity>
	<fallback>en_ZA</fallback>
	<localeDisplayNames>
		<languages>
			<language type="af">isiBhunu</language>
			<language type="am">Isi-Amaharikhi</language>
			<language type="ar">isi-Alabhu</language>
			<language type="as">Assamese</language>
			<language type="az">Isi-Azebhayijani</language>
			<language type="be">IsiBhelarashiyani</language>
			<language type="bg">Isi-Bulgaria</language>
			<language type="bh">IsiBhihari</language>
			<language type="bn">IsiBhengali</language>
			<language type="br">isihlobo sase Britain</language>
			<language type="bs">IsiBhosiniyani</language>
			<language type="ca">IsiKhathalani</language>
			<language type="cs">Isi-Czech</language>
			<language type="cy">IsiWelshi</language>
			<language type="da">IsiDenishi</language>
			<language type="de">isiJalimani</language>
			<language type="el">IsiGreki</language>
			<language type="en">isiNgisi</language>
			<language type="eo">Isi-Esperanto</language>
			<language type="es">isiSpeyini</language>
			<language type="et">Isi-Esistoniya</language>
			<language type="eu">Isi-Basque</language>
			<language type="fa">IsiPheshiyani</language>
			<language type="fi">isiFinnish</language>
			<language type="fil">IsiThagalogi</language>
			<language type="fo">Isifaro</language>
			<language type="fr">isiFulentshi</language>
			<language type="fy">IsiFriziyani</language>
			<language type="ga">Isi-Irishi</language>
			<language type="gd">I-Scots Gaelic</language>
			<language type="gl">Isi-Galashiya</language>
			<language type="gn">Gurani</language>
			<language type="gu">IsiGujarati</language>
			<language type="he">IsiHebheru</language>
			<language type="hi">isiHindi</language>
			<language type="hr">Isi-Croatia</language>
			<language type="hu">IsiHangari</language>
			<language type="hy">Armenian</language>
			<language type="ia">Izilimi ezihlangene</language>
			<language type="id">Isi-Indonesia</language>
			<language type="ie">Izilimu</language>
			<language type="is">Isi-Icelandic</language>
			<language type="it">isItalian</language>
			<language type="ja">IsiJaphani</language>
			<language type="jv">IsiJavanisi</language>
			<language type="ka">IsiJojiyani</language>
			<language type="km">Cambodian</language>
			<language type="kn">Ikhanada</language>
			<language type="ko">IsiKoriya</language>
			<language type="ku">ulimu lwama Kudishi</language>
			<language type="ky">Kyrgyz</language>
			<language type="la">IsiLathini</language>
			<language type="ln">Lingala</language>
			<language type="lo">Laothian</language>
			<language type="lt">Isi-Lithuanian</language>
			<language type="lv">Isi-Latvian</language>
			<language type="mk">IsiMakhedoniya</language>
			<language type="ml">IsiMalayami</language>
			<language type="mn">Mongolian</language>
			<language type="mr">IsiMarathi</language>
			<language type="ms">IsiMalayi</language>
			<language type="mt">IsiMalithize</language>
			<language type="ne">IsiNepali</language>
			<language type="nl">Isi-Dutch</language>
			<language type="nn">IsiNowejiyani (Nynorsk)</language>
			<language type="no">IsiNoweyi</language>
			<language type="oc">Isi-Osithani</language>
			<language type="or">Oriya</language>
			<language type="pa">IsiPhunjabi</language>
			<language type="pl">IsiPholisi</language>
			<language type="ps">Pashto</language>
			<language type="pt">IsiPotukezi</language>
			<language type="pt_BR">Isiputukezi (Brazil)</language>
			<language type="pt_PT">IsiPotukezi (Ephothugali)</language>
			<language type="ro">IsiRomani</language>
			<language type="ru">IsiRashiya</language>
			<language type="sa">Sanskrit</language>
			<language type="sd">Sindhi</language>
			<language type="sh">Serbo-Croatian</language>
			<language type="si">IsiSinhalese</language>
			<language type="sk">IsiSlovaki</language>
			<language type="sl">IsiSlovakiyani</language>
			<language type="so">Somali</language>
			<language type="sq">Isi-Albania</language>
			<language type="sr">Isi-Sebhiya</language>
			<language type="st">isiSuthu</language>
			<language type="su">IsiSundanizi</language>
			<language type="sv">IsiSwidishi</language>
			<language type="sw">isiSwahili</language>
			<language type="ta">IsiThamil</language>
			<language type="te">IsiThelugu</language>
			<language type="th">IsiThayi</language>
			<language type="ti">IsiTigrinya</language>
			<language type="tk">umuntu wase Turkmenistan.</language>
			<language type="tlh">IsiKlingoni</language>
			<language type="tr">IsiThekishi</language>
			<language type="tw">Twi</language>
			<language type="ug">Uighur</language>
			<language type="uk">Isi-Ukrain</language>
			<language type="ur">Isi-Udu</language>
			<language type="uz">Isi-Uzibheki</language>
			<language type="vi">IsiVietnamise</language>
			<language type="xh">isiXhosa</language>
			<language type="yi">ulimu olwi Yidish</language>
			<language type="zu">isiZulu</language>
		</languages>
		<territories>
			<territory type="ZA">iNingizimu Afrika</territory>
		</territories>
	</localeDisplayNames>
	<characters>
		<exemplarCharacters>[a b {bh} c {ch} d {dl} {dy} e f g {gc} {gq} {gx} h {hh} {hl} i j k {kh} {kl} {kp} l m n {nc} {ngc} {ngq} {ngx} {nhl} {nk} {nkc} {nkq} {nkx} {nq} {ntsh} {nx} {ny} o p {ph} q {qh} r {rh} s {sh} t {th} {tl} {ts} {tsh} u v w x {xh} y z]</exemplarCharacters>
		<exemplarCharacters type="currencySymbol">[a b c d e f g h i j k l m n o p q r s t u v w x y z]</exemplarCharacters>
		<exemplarCharacters type="index">[A B C D E F G H I J K L M N O P Q R S T U V W X Y Z]</exemplarCharacters>
	</characters>
	<delimiters>
		<quotationStart>'</quotationStart>
		<quotationEnd>'</quotationEnd>
		<alternateQuotationStart>"</alternateQuotationStart>
		<alternateQuotationEnd>"</alternateQuotationEnd>
	</delimiters>
	<dates>
		<calendars>
			<calendar type="gregorian">
				<months>
					<monthContext type="format">
						<monthWidth type="abbreviated">
							<month type="1">Jan</month>
							<month type="2">Feb</month>
							<month type="3">Mas</month>
							<month type="4">Apr</month>
							<month type="5">Mey</month>
							<month type="6">Jun</month>
							<month type="7">Jul</month>
							<month type="8">Aga</month>
							<month type="9">Sep</month>
							<month type="10">Okt</month>
							<month type="11">Nov</month>
							<month type="12">Dis</month>
						</monthWidth>
						<monthWidth type="wide">
							<month type="1">Januwari</month>
							<month type="2">Februwari</month>
							<month type="3">Mashi</month>
							<month type="4">Apreli</month>
							<month type="5">Meyi</month>
							<month type="6">Juni</month>
							<month type="7">Julayi</month>
							<month type="8">Agasti</month>
							<month type="9">Septhemba</month>
							<month type="10">Okthoba</month>
							<month type="11">Novemba</month>
							<month type="12">Disemba</month>
						</monthWidth>
					</monthContext>
					<monthContext type="stand-alone">
						<monthWidth type="narrow">
							<month type="1">J</month>
							<month type="2">F</month>
							<month type="3">M</month>
							<month type="4">A</month>
							<month type="5">M</month>
							<month type="6">J</month>
							<month type="7">J</month>
							<month type="8">A</month>
							<month type="9">S</month>
							<month type="10">O</month>
							<month type="11">N</month>
							<month type="12">D</month>
						</monthWidth>
						<monthWidth type="wide">
							<month type="1">uJanuwari</month>
							<month type="2">uFebruwari</month>
							<month type="3">uMashi</month>
							<month type="4">u-Apreli</month>
							<month type="5">uMeyi</month>
							<month type="6">uJuni</month>
							<month type="7">uJulayi</month>
							<month type="8">uAgasti</month>
							<month type="9">uSepthemba</month>
							<month type="10">u-Okthoba</month>
							<month type="11">uNovemba</month>
							<month type="12">uDisemba</month>
						</monthWidth>
					</monthContext>
				</months>
				<days>
					<dayContext type="format">
						<dayWidth type="abbreviated">
							<day type="sun">Son</day>
							<day type="mon">Mso</day>
							<day type="tue">Bil</day>
							<day type="wed">Tha</day>
							<day type="thu">Sin</day>
							<day type="fri">Hla</day>
							<day type="sat">Mgq</day>
						</dayWidth>
						<dayWidth type="wide">
							<day type="sun">Sonto</day>
							<day type="mon">Msombuluko</day>
							<day type="tue">Lwesibili</day>
							<day type="wed">Lwesithathu</day>
							<day type="thu">uLwesine</day>
							<day type="fri">Lwesihlanu</day>
							<day type="sat">Mgqibelo</day>
						</dayWidth>
					</dayContext>
					<dayContext type="stand-alone">
						<dayWidth type="narrow">
							<day type="sun">S</day>
							<day type="mon">M</day>
							<day type="tue">B</day>
							<day type="wed">T</day>
							<day type="thu">S</day>
							<day type="fri">H</day>
							<day type="sat">M</day>
						</dayWidth>
					</dayContext>
				</days>
				<dateFormats>
					<dateFormatLength type="full">
						<dateFormat>
							<pattern>EEEE dd MMMM y</pattern>
						</dateFormat>
					</dateFormatLength>
					<dateFormatLength type="long">
						<dateFormat>
							<pattern>d MMMM y</pattern>
						</dateFormat>
					</dateFormatLength>
					<dateFormatLength type="medium">
						<dateFormat>
							<pattern>d MMM y</pattern>
						</dateFormat>
					</dateFormatLength>
					<dateFormatLength type="short">
						<dateFormat>
							<pattern>yyyy-MM-dd</pattern>
						</dateFormat>
					</dateFormatLength>
				</dateFormats>
				<timeFormats>
					<timeFormatLength type="full">
						<timeFormat>
							<pattern>h:mm:ss a zzzz</pattern>
						</timeFormat>
					</timeFormatLength>
					<timeFormatLength type="long">
						<timeFormat>
							<pattern>h:mm:ss a z</pattern>
						</timeFormat>
					</timeFormatLength>
					<timeFormatLength type="medium">
						<timeFormat>
							<pattern>h:mm:ss a</pattern>
						</timeFormat>
					</timeFormatLength>
					<timeFormatLength type="short">
						<timeFormat>
							<pattern>h:mm a</pattern>
						</timeFormat>
					</timeFormatLength>
				</timeFormats>
			</calendar>
		</calendars>
	</dates>
	<numbers>
		<symbols>
			<decimal>,</decimal>
			<group> </group>
		</symbols>
		<decimalFormats>
			<decimalFormatLength>
				<decimalFormat>
					<pattern>#,##0.###</pattern>
				</decimalFormat>
			</decimalFormatLength>
		</decimalFormats>
		<scientificFormats>
			<scientificFormatLength>
				<scientificFormat>
					<pattern>#E0</pattern>
				</scientificFormat>
			</scientificFormatLength>
		</scientificFormats>
		<percentFormats>
			<percentFormatLength>
				<percentFormat>
					<pattern>#,##0%</pattern>
				</percentFormat>
			</percentFormatLength>
		</percentFormats>
		<currencyFormats>
			<currencyFormatLength>
				<currencyFormat>
					<pattern>¤#,##0.00</pattern>
				</currencyFormat>
			</currencyFormatLength>
		</currencyFormats>
	</numbers>
	<posix>
		<messages>
			<yesstr>yebo:y</yesstr>
			<nostr>cha:c</nostr>
		</messages>
	</posix>
</ldml>


text:
<?php

namespace CDMonte\SuiteCRMBridgeBundle\DAO\EndPoint;

use CDMonte\SuiteCRMBridgeBundle\DAO\EndPoint\V4_1\EndPoint;

/**
 * Class EndPointFactory
 * @package CDMonte\SuiteCRMBridgeBundle\DAO\EndPoint
 */
class EndPointFactory
{
    /** @var EndPointInterface $instance */
    private $instance;

    /**
     * EndPointFactory constructor.
     * @param $version
     * @throws \Exception
     */
    public function __construct($version)
    {
        if ($version === "V4_1") {
            $this->instance = new EndPoint();
        } else {
            throw new \Exception(sprintf("No endpoint for version %s available.", $version));
        }
    }

    /**
     * @return EndPointInterface
     */
    public function getInstance()
    {
        return $this->instance;
    }
}


text:
var webpack = require('webpack')
var getConfig = require('hjs-webpack')

var config = getConfig({
  in: 'public/ide-main.js',
  out: 'output',

  output: {
    filename: 'bundle.js',
    cssFilename: 'bundle.css'
  },

  html: false,
  clearBeforeBuild: true,

  devServer: {
    hot: false,
    contentBase: __dirname
  }
})

config.plugins.push(new webpack.SourceMapDevToolPlugin({
  filename: '[file].map'
}))
config.devtool = 'eval-source-map'

config.module.rules.push({
  test: /\.purs$/,
  use: [
    {
      loader: 'purs-loader',
      options: {
        src: [
          'bower_components/purescript-*/src/**/*.purs',
          'src/**/*.purs'
        ],
        bundle: false,
        psc: 'psa',
        watch: false,
        pscIde: false
      }
    }
  ]
})

config.resolve.modules = ['node_modules', 'bower_components']
config.resolve.extensions.push('.purs')

module.exports = config


text:
function start() {
	set -x

	sudo ovs-vsctl add-br br-int

	sudo ip netns add vm1
	sudo ip link add vm1-eth0 type veth peer name eth0 netns vm1
	sudo ip link set vm1-eth0 up

	sudo ip netns exec vm1 ip link set eth0 up
	sudo ip netns exec vm1 ip address add $1 dev eth0

	sudo ovs-vsctl add-port br-int vm1-eth0

	if [ ! -z "$2" ]; then
		sudo ip netns add vm2
		sudo ip link add vm2-eth0 type veth peer name eth0 netns vm2
		sudo ip link set vm2-eth0 up

		sudo ip netns exec vm2 ip link set eth0 up
		sudo ip netns exec vm2 ip address add $2 dev eth0

		sudo ovs-vsctl add-port br-int vm2-eth0
	fi
}

function stop() {
	set -x

	sudo ovs-vsctl del-br br-int
	sudo ip link del vm1-eth0
	sudo ip netns del vm1
	sudo ip link del vm2-eth0
	sudo ip netns del vm2
}

if [ "$1" == "start" ]; then
	if [ -z "$2" ]; then
		echo "Usage: $0 start <ns ip/mask> [ns2 ip/mask]"
		exit 1
	fi

	start $2 $3
else
	stop
fi


text:
    <audio id="{{alert.id}}-beep">
        <source src="resources/beep.ogg" type="audio/ogg"></source>
    </audio>
    <audio id="{{alert.id}}-beepbeep">
        <source src="resources/beep.ogg" type="audio/ogg"></source>
    </audio>

        {{alert.id}}

Base

100

Base

100

Base

100

Base

100

Base

100

        <form id="{{alert.id}}-form">
            <input type="submit" style="position: absolute; left: -9999px; width: 1px; height: 1px;" tabindex="-1" />

                At

                    <input id="{{alert.id}}-settings-at" type="text" />

                Binding

                    <select id="{{alert.id}}-settings-binding">
                        <option value="-1"></option>
                        <option value="1">1</option>
                        <option value="2">2</option>
                        <option value="3">3</option>
                        <option value="4">4</option>
                        <option value="5">5</option>
                        <option value="6">6</option>
                        <option value="7">7</option>
                        <option value="8">8</option>
                        <option value="9">9</option>
                        <option value="0">0</option>
                    </select>

                Color

                    <select id="{{alert.id}}-settings-color">
                        {{#each colors}}
                        <option value="{{this.value}}">{{this.name}}</option>
                        {{/each}}
                    </select>

                Type

                    <select id="{{alert.id}}-settings-type">
                        {{#each types}}
                        <option value="{{this}}">{{this}}</option>
                        {{/each}}
                    </select>

                Name

                    <input id="{{alert.id}}-settings-name" type="text" />

                Duration

                Seconds

                Duration

                    <input id="{{alert.id}}-settings-custom_duration" type="text" />

                Seconds

                Repeat

                    <input id="{{alert.id}}-settings-repeat" type="checkbox" />

                    <select id="{{alert.id}}-settings-repeat_for">
                        <option value="-1">Infinite</option>
                        <option value="1">1</option>
                        <option value="2">2</option>
                        <option value="3">3</option>
                        <option value="4">4</option>
                        <option value="5">5</option>
                        <option value="6">6</option>
                        <option value="7">7</option>
                        <option value="8">8</option>
                        <option value="9">9</option>
                    </select>

                Countdowns

                Buffer

                    <input id="{{alert.id}}-settings-repeat_buffer" type="text" />

                Seconds

                Beep

                    at Finish
                    <input id="{{alert.id}}-settings-beep" type="checkbox" />

                    at Restart
                    <input id="{{alert.id}}-settings-repeat_beep" type="checkbox" />

                Flash

                    at Finish
                    <input id="{{alert.id}}-settings-flash" type="checkbox" />

                    at Restart
                    <input id="{{alert.id}}-settings-repeat_flash" type="checkbox" />

        </form>

Start/Reset

Remove


text:
/*
 * Tiles.h
 *
 *  Created on: 27.05.2012
 *
 */

#ifndef TILES_H_
#define TILES_H_

#include "basic_types.h"
#include "map/Constants.h"

struct RegionMap
{
	float latitude;
	float longitude;
	int seed;
	char* seed_string;
	UINT texture_id;
	RegionMap() : seed_string(0) {}
};

enum {
	TILE_TYPE_NONE = 0,
	TILE_TYPE_NORMAL,
	TILE_TYPE_BLOCK
};

struct TileInfo
{
	unsigned int picture;
	float passability;
	int texture;
	char* id;
	TileInfo() : picture(), passability(), texture(), id(0) {};
};

struct MapTile
{
	unsigned int TileID;
	s2i Real;
	s2i pos;
	TileInfo* Type;
	void create( signed int x, signed int y );
	MapTile( ) : TileID(), Type(0) {};

};

#endif /* TILES_H_ */


text:
/**
 * Example script getting the edit token
 */
"use strict";

const Bot = require(".."),
  wikia = new Bot({
    server: "nordycka.wikia.com",
    path: "",
    debug: true,
  }),
  wikipedia = new Bot({
    server: "pl.wikipedia.org",
    path: "/w",
    debug: true,
  });

wikia.getToken("Main_page", "edit", function (err, token) {
  if (err) {
    wikia.log(err);
  }
  wikia.log("Wikia:", token);
});

wikipedia.getToken("Main_page", "edit", function (err, token) {
  if (err) {
    wikipedia.log(err);
  }
  wikipedia.log("Wikipedia:", token);
});


text:
package com.suscipio_solutions.consecro_mud.Abilities.Thief;
import com.suscipio_solutions.consecro_mud.Abilities.interfaces.Ability;
import com.suscipio_solutions.consecro_mud.Common.interfaces.CMMsg;
import com.suscipio_solutions.consecro_mud.MOBS.interfaces.MOB;
import com.suscipio_solutions.consecro_mud.core.CMLib;
import com.suscipio_solutions.consecro_mud.core.CMath;
import com.suscipio_solutions.consecro_mud.core.interfaces.Environmental;

public class Thief_Countertracking extends ThiefSkill
{
	@Override public String ID() { return "Thief_Countertracking"; }
	private final static String localizedName = CMLib.lang().L("Counter-Tracking");
	@Override public String name() { return localizedName; }
	@Override public String displayText(){ return "";}
	@Override protected int canAffectCode(){return CAN_MOBS;}
	@Override protected int canTargetCode(){return 0;}
	@Override public int abstractQuality(){return Ability.QUALITY_INDIFFERENT;}
	@Override public boolean isAutoInvoked(){return true;}
	@Override public boolean canBeUninvoked(){return false;}
	@Override public int classificationCode() {   return Ability.ACODE_SKILL|Ability.DOMAIN_STEALTHY; }

	@Override
	public boolean okMessage(final Environmental myHost, final CMMsg msg)
	{
		if(!(affected instanceof MOB))
			return super.okMessage(myHost,msg);

		final MOB mob=(MOB)affected;
		if((!msg.amISource(mob))
		&&(msg.target()==mob)
		&&(msg.tool() instanceof Ability)
		&&(proficiencyCheck(mob,0,false))
		&&(CMath.bset(((Ability)msg.tool()).flags(),Ability.FLAG_TRACKING)))
		{
			msg.source().tell(L("You can't get a bead on him."));
			return false;
		}
		return super.okMessage(myHost,msg);
	}
}


text:
<?php

namespace Bamboo\Feeds;

use Bamboo\Client;

class Base
{

    public function __construct($params = array()) {
        $this->_response = Client::getInstance()->request(
            $this->_feed, $params
        );
    }

    protected function _buildModels($elements) {
        $models = array();

        foreach ( $elements as $element ) {
            $className = $this->_className($element->type);
            $models[] = new $className($element);
        }

        return $models;
    }

    /*
     * Translate Class name into Model name.
     *  $words[0] as most only have first index.
     *  Exept Programme and Group which have 'Large' at index 2
     *
     * @return string $return
     */
    protected function _className($string) {
        $words = explode('_', mb_strtoupper($string, "UTF-8"));
        $return = "Bamboo\Models\\";
        $return .=  $this->_ucFirstChar($words[0]);
        return $return;
    }

    /*
     * Upper case first character, lower case all following.
     *
     * @return string
     */
    private function _ucFirstChar($string) {
        $encoding = "UTF-8";

        return mb_strtoupper(
            mb_substr($string, 0, 1, $encoding),
            $encoding
        ) .
        mb_strtolower(
            mb_substr(
                $string, 1, mb_strlen($string),
                $encoding
            ),
            $encoding
        );
    }

}


text:
from scrapy import Field, Item
from scrapy.contrib.loader import ItemLoader
from scrapy.contrib.loader.processor import TakeFirst, MapCompose, Compose

class BoredpandaScraperItem(Item):
    title = Field()  # Storing article title
    content = Field()  # Storing article textual content.
    votes = Field()  # Storing article up votes.
    images = Field()  # Will be populated with image file system paths when downloaded.
    image_urls = Field()  # Storing all article images urls for later download.
    date_created = Field()  # Storing UTC date when item was scraped
    url = Field()  # URL of a page.

class BoredpandaScraperItemLoader(ItemLoader):
    # Content is a list of strings. Those should be
    # concatenated and exported as a string.
    content_in = Compose(lambda x: '\n'.join(x))
    content_out = TakeFirst()

    # Votes gets scraped as a one item list
    # and should be exported as str. Same for url.
    votes_out = TakeFirst()

    url_out = TakeFirst()

    title_in = MapCompose(lambda x: x.strip())
    title_out = TakeFirst()

    date_created_out = TakeFirst()


text:
> Simple grunt plugin to create a list of files and write it to a json file

## Getting Started
This plugin requires Grunt.

If you haven't used [Grunt](http://gruntjs.com/) before, be sure to check out the [Getting Started](http://gruntjs.com/getting-started) guide, as it explains how to create a [Gruntfile](http://gruntjs.com/sample-gruntfile) as well as install and use Grunt plugins. Once you're familiar with that process, you may install this plugin with this command:

```shell
npm install grunt-files-to-json --save-dev
```

Once the plugin has been installed, it may be enabled inside your Gruntfile with this line of JavaScript:

```js
grunt.loadNpmTasks('grunt-files-to-json');
```

## The "files_to_json" task

### Overview
In your project's Gruntfile, add a section named `files_to_json` to the data object passed into `grunt.initConfig()`.

```js
grunt.initConfig({
  files_to_json: {
    files: {
      src: // [pattern],
      dest: // output file,
        options: {
          name: // optional name
       }
    }

  },
})
```

### Options

#### options.name
Type: `String`
Default value: `'item'`

### Usage Examples

```js
grunt.initConfig({
  files_to_json: {
    files: {
      src: '<%= distdir %>/themes/*/*.css',
        dest: '<%= distdir %>/themes.json',
        options: {
          name: 'theme'
       }
    }
  },
});
```
#### Example output file

```json
{ "results": [
      {"name":"theme_1", "url":"/themes/default/8909873.style.css"},
      {"name":"theme_2", "url":"/themes/comso/8934573.style.css"},
      {"name":"theme_3", "url":"/themes/minimal/8923473.style.css"}
]}
```

## Running the tests

After you have cloned the repo execute grunt test.

## Release History
_(Nothing yet)_

## License
Copyright (c) 2014 Nik G. Licensed under the MIT license.


text:
import { Component } from '@angular/core';

import { Item } from '../../models/item';
import { Topics } from '../../providers/providers';

@Component({
    selector: 'topics-list',
    templateUrl: 'topics-list.html'
})
export class TopicsListPage {
    currentTopics: Item[];

    constructor(public topics: Topics) {
        this.currentTopics = topics.query();
    }

    subscribeToTopic(slidingItem, topic) {
        this.topics.subscribe(topic);
        slidingItem.close();
    }

    unsubscribeToTopic(slidingItem, topic) {
        this.topics.unsubscribe(topic);
        slidingItem.close();
    }
}


text:
layout: default
modal-id: 2
company-name: Stony Brook University
location: Stony Brook, NY
date: 2014-12-20
timeline: Fall 2014
position-title: Teaching Assistant, Digital System Design
number-of-lines: 2
detailed: no
description: |

Instructed a classroom of 20 students on designing applications using logic gates.

Assisted individual design groups in hardware testing, which included optimization of the hardware-software interface.

number-of-images: 1
img1: gates.jpeg
tools-used: Logic gates, Oscilloscope, Function Generator, Power Supplies, Xilinx, Verilog
link:
tags: [Logic gates, Oscilloscope, Function Generator, Power Supplies, Xilinx, Verilog]
---


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Microsoft.Phone.Tasks;
using System.Diagnostics;
using System.IO.IsolatedStorage;
using TappyPlaneComp;

namespace TappyPlane
{
    public partial class MainPage : PhoneApplicationPage
    {
        private Direct3DInterop m_d3dInterop = new Direct3DInterop();
        private object m_d3dContentProvider;

        public MainPage()
        {
            InitializeComponent();
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            base.OnBackKeyPress(e);

            if (m_d3dInterop.onBackPressed())
            {
                e.Cancel = true;
            }
        }

        private void DrawingSurface_Loaded(object sender, RoutedEventArgs e)
        {
            // Set window bounds in dips
            m_d3dInterop.WindowBounds = new Windows.Foundation.Size((float)DrawingSurface.ActualWidth, (float)DrawingSurface.ActualHeight);

            // Set native resolution in pixels
            m_d3dInterop.NativeResolution = new Windows.Foundation.Size((float)Math.Floor(DrawingSurface.ActualWidth * Application.Current.Host.Content.ScaleFactor / 100.0f + 0.5f), (float)Math.Floor(DrawingSurface.ActualHeight * Application.Current.Host.Content.ScaleFactor / 100.0f + 0.5f));

            // Set render resolution to the full native resolution
            m_d3dInterop.RenderResolution = m_d3dInterop.NativeResolution;

            // Hook-up native component to DrawingSurface
            if (m_d3dContentProvider == null)
            {
                m_d3dContentProvider = m_d3dInterop.CreateContentProvider();
            }

            DrawingSurface.SetContentProvider(m_d3dContentProvider);
            DrawingSurface.SetManipulationHandler(m_d3dInterop);

            m_d3dInterop.setWinRtCallback(new WinRtCallback(ProcessCallback));
        }

        async private void ProcessCallback(String command, String param)
        {
            Console.WriteLine("Incoming callback from C++ : " + command);

            if (command.Equals("GAME_OVER"))
            {
                int score = m_d3dInterop.getScore();

                IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;

                int bestScore = 0;

                if (settings.Contains("BEST_SCORE"))
                {
                    bestScore = Convert.ToInt32(settings["BEST_SCORE"]);
                }

                if (score >= bestScore)
                {
                    if (settings.Contains("BEST_SCORE"))
                    {
                        settings.Remove("BEST_SCORE");
                    }
                    String bestScoreString = Convert.ToString(score);
                    settings.Add("BEST_SCORE", bestScoreString);
                    settings.Save();
                }

                m_d3dInterop.setBestScore(Convert.ToInt32(settings["BEST_SCORE"]));
            }
        }
    }
}


text:
app.controller('AdvancedSearchController', function ($rootScope, $scope, $http, $routeParams, $location) {

    var queries = {};
    var loadRelevant = function (term) {
        if (queries[term]) {
            $scope.relevant = queries[term];
            return;
        }
        $http.get('/api/relevant-search?term=' + term + '&resources=contentNodes,courses')
            .success(function (data) {
                $scope.relevant = _.take(_.shuffle(data), 5);
                queries[term] = $scope.relevant;
                setBusy(false);
            });
    };

    var loadPopular = function (term) {
        $http.get('/api/relevant-search?term=' + term + '&resources=courses')
            .success(function (data) {
                orderPopular(data);
                setBusy(false);
            });
    };

    var orderPopular = function (data) {
        $scope.popular = _.take(_.sortBy(data, $scope.popularBy, 'desc'), 10);
    };

    var search = function () {

        var term = $scope.searchTerm;

        // Check if search is empty
        if (!term || term.length == 0) {
            // Clear previous result
            $scope.result = null;
            $scope.relevant = null;
            return;
        }

        setBusy(true);

        // Build query
        var user = $rootScope.user;
        var query = '?term=' + term;

        // Configure resource query
        var allowedResources = [];
        for (var resourceType in $scope.resources) {
            var r = $scope.resources[resourceType];
            if (r.selected) {
                allowedResources.push(resourceType);
            }
        }
        query += '&resources=' + allowedResources.join();

        // Configure network query
        switch ($scope.network) {
            case "owned":
                query += '&owner=' + user._id;
                break;
        }

        // Find matching results
        $http.get('/api/advanced-search' + query)
            .success(function (data) {

                var startAt = $scope.filterDate.startDate;
                var endAt = $scope.filterDate.endDate;

                if (startAt && endAt) {
                    $scope.result = _.filter(data, function (o) {
                        return $scope.filterDate.startDate.isBefore(o.updated) &&
                            $scope.filterDate.endDate.isAfter(o.updated);
                    });
                }
                else {
                    $scope.result = data;
                }

                setBusy(false);

                loadRelevant(term);
                loadPopular(term);
            });
    };

    var setBusy = function (isBusy) {
        $scope.isBusy = isBusy;
    };

    function init() {

        setBusy(false);
        $scope.popularBy = '-activity';
        $scope.result = null;
        $scope.relevant = null;
        $scope.network = 'global';
        $scope.resources = {
            categories: {selected: true},
            contentNodes: {selected: true},
            courses: {selected: true},
            videoAnnotations: {selected: false},
            pdfAnnotations: {selected: false},
            extResources: {selected: false}
        };

        $scope.filterDate = {startDate: null, endDate: null};

        // Monitor changes of filters
        $scope.$watch('network', search);
        $scope.$watch('resources', search, true);
        $scope.$watch('filterDate', search, true);
        $scope.$watch('popularBy', function () {
            loadPopular($scope.searchTerm);
        }, true);

        // Subscribe to menu query text changes
        $scope.$on('searchQueryChanged', function (event, args) {
            $scope.searchTerm = args.state;
            search();
        })
    }

    // Initialize controller
    init();
});


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.facebook.presto.orc.reader;

import com.facebook.presto.orc.OrcCorruptionException;
import com.facebook.presto.orc.StreamDescriptor;
import com.facebook.presto.orc.metadata.ColumnEncoding;
import com.facebook.presto.orc.stream.BooleanInputStream;
import com.facebook.presto.orc.stream.InputStreamSource;
import com.facebook.presto.orc.stream.InputStreamSources;
import com.facebook.presto.orc.stream.LongInputStream;
import com.facebook.presto.spi.block.Block;
import com.facebook.presto.spi.block.BlockBuilder;
import com.facebook.presto.spi.block.BlockBuilderStatus;
import com.facebook.presto.spi.type.Type;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

import java.io.IOException;
import java.util.List;

import static com.facebook.presto.orc.metadata.Stream.StreamKind.DATA;
import static com.facebook.presto.orc.metadata.Stream.StreamKind.PRESENT;
import static com.facebook.presto.orc.metadata.Stream.StreamKind.SECONDARY;
import static com.facebook.presto.orc.stream.MissingInputStreamSource.missingStreamSource;
import static com.google.common.base.MoreObjects.toStringHelper;
import static java.util.Objects.requireNonNull;

public class TimestampStreamReader
        implements StreamReader
{
    private static final int MILLIS_PER_SECOND = 1000;

    private final StreamDescriptor streamDescriptor;
    private final long baseTimestampInSeconds;

    private int readOffset;
    private int nextBatchSize;

    @Nonnull
    private InputStreamSource<BooleanInputStream> presentStreamSource = missingStreamSource(BooleanInputStream.class);
    @Nullable
    private BooleanInputStream presentStream;
    private boolean[] nullVector = new boolean[0];

    @Nonnull
    private InputStreamSource<LongInputStream> secondsStreamSource = missingStreamSource(LongInputStream.class);
    @Nullable
    private LongInputStream secondsStream;

    @Nonnull
    private InputStreamSource<LongInputStream> nanosStreamSource = missingStreamSource(LongInputStream.class);
    @Nullable
    private LongInputStream nanosStream;

    private long[] secondsVector = new long[0];
    private long[] nanosVector = new long[0];

    private boolean rowGroupOpen;

    public TimestampStreamReader(StreamDescriptor streamDescriptor, DateTimeZone hiveStorageTimeZone)
    {
        this.streamDescriptor = requireNonNull(streamDescriptor, "stream is null");
        this.baseTimestampInSeconds = new DateTime(2015, 1, 1, 0, 0, requireNonNull(hiveStorageTimeZone, "hiveStorageTimeZone is null")).getMillis() / MILLIS_PER_SECOND;
    }

    @Override
    public void prepareNextRead(int batchSize)
    {
        readOffset += nextBatchSize;
        nextBatchSize = batchSize;
    }

    @Override
    public Block readBlock(Type type)
            throws IOException
    {
        if (!rowGroupOpen) {
            openRowGroup();
        }

        if (readOffset > 0) {
            if (presentStream != null) {
                // skip ahead the present bit reader, but count the set bits
                // and use this as the skip size for the data reader
                readOffset = presentStream.countBitsSet(readOffset);
            }
            if (readOffset > 0) {
                if (secondsStream == null) {
                    throw new OrcCorruptionException("Value is not null but seconds stream is not present");
                }
                if (nanosStream == null) {
                    throw new OrcCorruptionException("Value is not null but nanos stream is not present");
                }

                secondsStream.skip(readOffset);
                nanosStream.skip(readOffset);
            }
        }

        if (secondsVector.length < nextBatchSize) {
            secondsVector = new long[nextBatchSize];
        }
        if (nanosVector.length < nextBatchSize) {
            nanosVector = new long[nextBatchSize];
        }

        BlockBuilder builder = type.createBlockBuilder(new BlockBuilderStatus(), nextBatchSize);
        if (presentStream == null) {
            if (secondsStream == null) {
                throw new OrcCorruptionException("Value is not null but seconds stream is not present");
            }
            if (nanosStream == null) {
                throw new OrcCorruptionException("Value is not null but nanos stream is not present");
            }

            secondsStream.nextLongVector(nextBatchSize, secondsVector);
            nanosStream.nextLongVector(nextBatchSize, nanosVector);

            // merge seconds and nanos together
            for (int i = 0; i < nextBatchSize; i++) {
                type.writeLong(builder, decodeTimestamp(secondsVector[i], nanosVector[i], baseTimestampInSeconds));
            }
        }
        else {
            if (nullVector.length < nextBatchSize) {
                nullVector = new boolean[nextBatchSize];
            }
            int nullValues = presentStream.getUnsetBits(nextBatchSize, nullVector);
            if (nullValues != nextBatchSize) {
                if (secondsStream == null) {
                    throw new OrcCorruptionException("Value is not null but seconds stream is not present");
                }
                if (nanosStream == null) {
                    throw new OrcCorruptionException("Value is not null but nanos stream is not present");
                }

                secondsStream.nextLongVector(nextBatchSize, secondsVector, nullVector);
                nanosStream.nextLongVector(nextBatchSize, nanosVector, nullVector);

                // merge seconds and nanos together
                for (int i = 0; i < nextBatchSize; i++) {
                    if (nullVector[i]) {
                        builder.appendNull();
                    }
                    else {
                        type.writeLong(builder, decodeTimestamp(secondsVector[i], nanosVector[i], baseTimestampInSeconds));
                    }
                }
            }
            else {
                for (int i = 0; i < nextBatchSize; i++) {
                    builder.appendNull();
                }
            }
        }

        readOffset = 0;
        nextBatchSize = 0;
        return builder.build();
    }

    private void openRowGroup()
            throws IOException
    {
        presentStream = presentStreamSource.openStream();
        secondsStream = secondsStreamSource.openStream();
        nanosStream = nanosStreamSource.openStream();
        rowGroupOpen = true;
    }

    @Override
    public void startStripe(InputStreamSources dictionaryStreamSources, List<ColumnEncoding> encoding)
            throws IOException
    {
        presentStreamSource = missingStreamSource(BooleanInputStream.class);
        secondsStreamSource = missingStreamSource(LongInputStream.class);
        nanosStreamSource = missingStreamSource(LongInputStream.class);

        readOffset = 0;
        nextBatchSize = 0;

        presentStream = null;
        secondsStream = null;
        nanosStream = null;

        rowGroupOpen = false;
    }

    @Override
    public void startRowGroup(InputStreamSources dataStreamSources)
            throws IOException
    {
        presentStreamSource = dataStreamSources.getInputStreamSource(streamDescriptor, PRESENT, BooleanInputStream.class);
        secondsStreamSource = dataStreamSources.getInputStreamSource(streamDescriptor, DATA, LongInputStream.class);
        nanosStreamSource = dataStreamSources.getInputStreamSource(streamDescriptor, SECONDARY, LongInputStream.class);

        readOffset = 0;
        nextBatchSize = 0;

        presentStream = null;
        secondsStream = null;
        nanosStream = null;

        rowGroupOpen = false;
    }

    @Override
    public String toString()
    {
        return toStringHelper(this)
                .addValue(streamDescriptor)
                .toString();
    }

    // This comes from the Apache Hive ORC code
    public static long decodeTimestamp(long seconds, long serializedNanos, long baseTimestampInSeconds)
    {
        long millis = (seconds + baseTimestampInSeconds) * MILLIS_PER_SECOND;
        long nanos = parseNanos(serializedNanos);

        // the rounding error exists because java always rounds up when dividing integers
        // -42001/1000 = -42; and -42001 % 1000 = -1 (+ 1000)
        // to get the correct value we need
        // (-42 - 1)*1000 + 999 = -42001
        // (42)*1000 + 1 = 42001
        if (millis < 0 && nanos != 0) {
            millis -= 1000;
        }
        // Truncate nanos to millis and add to mills
        return millis + (nanos / 1_000_000);
    }

    // This comes from the Apache Hive ORC code
    private static int parseNanos(long serialized)
    {
        int zeros = ((int) serialized) & 0b111;
        int result = (int) (serialized >>> 3);
        if (zeros != 0) {
            for (int i = 0; i <= zeros; ++i) {
                result *= 10;
            }
        }
        return result;
    }
}


text:
package com.example.lwk.beans.LWKAdapter;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.lwk.beans.Fragment.HomeFragment;
import com.example.lwk.beans.LWKModel.HomeList;
import com.example.lwk.beans.R;

import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/11/28.
 */
public class HomeAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements View.OnClickListener {

    private static final String TAG = HomeAdapter.class.getSimpleName();
    private List<HomeList> data;
    private LayoutInflater inflater;
    public static final int IS_HEADER = 0;
    public static final int IS_ITEM = 1;
    private Boolean loading;
    private SendImageMessage message;
    private OnItemClickListener listener;
    private RecyclerView mRecycerView;
    public void setListener(SendImageMessage message) {
        this.message = message;

    }
public void setitemListener(OnItemClickListener listener){
    this.listener=listener;
}

    public HomeAdapter(Context context) {
        data = new ArrayList<>();
        inflater = LayoutInflater.from(context);
    }
    @Override
    public void onAttachedToRecyclerView(RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
        mRecycerView=recyclerView;
    }

    @Override
    public void onDetachedFromRecyclerView(RecyclerView recyclerView) {
        super.onDetachedFromRecyclerView(recyclerView);
        mRecycerView=null;
    }

    public void updateRes(List<HomeList> data) {
        if (data != null) {
            this.data.clear();
            this.data.addAll(data);
            notifyDataSetChanged();
        }
    }

    ;

    public void addRes(List<HomeList> data) {
        if (data != null) {
            this.data.addAll(data);
            notifyDataSetChanged();
        }

    }

    @Override
    public void onClick(View v) {
        int childAdapterPosition = mRecycerView.getChildAdapterPosition(v);
        if (message!=null) {
            listener.onItemClick(childAdapterPosition);
        }
    }

    public class HeaderHolder extends RecyclerView.ViewHolder {
        ImageView imageView;
        ImageView imageView0;
        ImageView imageView1;
        ImageView imageView2;

        public HeaderHolder(View itemView) {
            super(itemView);
            imageView = (ImageView) itemView.findViewById(R.id.home_header_image);
            imageView0 = (ImageView) itemView.findViewById(R.id.home_header_image0);
            imageView1 = (ImageView) itemView.findViewById(R.id.home_header_image1);
            imageView2 = (ImageView) itemView.findViewById(R.id.home_header_image2);
        }
    }

    public class ItemViewHolder extends RecyclerView.ViewHolder {
        ImageView imageView;
        TextView caseName;
        TextView mainDesc;
        TextView comment;

        public ItemViewHolder(View itemView) {
            super(itemView);
            imageView = (ImageView) itemView.findViewById(R.id.home_item_mainPic);
            caseName = (TextView) itemView.findViewById(R.id.home_item_caseName);
            mainDesc = (TextView) itemView.findViewById(R.id.home_item_mainDesc);
            comment = (TextView) itemView.findViewById(R.id.home_item_comment);
        }
    }

    @Override
    public int getItemViewType(int position) {
        if (position == 0) {
            return IS_HEADER;
        } else {
            return IS_ITEM;
        }
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == IS_HEADER) {
            return new HeaderHolder(inflater.inflate(R.layout.home_header, parent, false));
        } else {
            return new ItemViewHolder(inflater.inflate(R.layout.home_item, parent, false));
        }
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof HeaderHolder) {
            x.image().bind(((HeaderHolder) holder).imageView, data.get(position).getHea_Image());
            x.image().bind(((HeaderHolder) holder).imageView0, data.get(position).getHea_Image0());
            x.image().bind(((HeaderHolder) holder).imageView1, data.get(position).getHea_Image1());
            x.image().bind(((HeaderHolder) holder).imageView2, data.get(position).getHea_Image2());

        } else if (holder instanceof ItemViewHolder) {
            ((ItemViewHolder) holder).caseName.setText(data.get(position).getCaseName());
            ((ItemViewHolder) holder).mainDesc.setText(data.get(position).getMainDesc());
            ((ItemViewHolder) holder).comment.setText("评论" + data.get(position).getComment());
            x.image().bind(((ItemViewHolder) holder).imageView, data.get(position).getItem_Image());
            loading = ((ItemViewHolder) holder).mainDesc.getText() != null;
            message.sendload(loading);
        }

        holder.itemView.setOnClickListener(this);
    }

    @Override
    public int getItemCount() {
       // Log.e(TAG, "getItemCount: "+data.size() );
        return data != null ? data.size()  : 0;
    }
    public String GetId(int position){
        return data.get(position).getId();
    }
    public interface SendImageMessage {
        void sendload(Boolean load);
    }
    public interface OnItemClickListener{
        void onItemClick(int position);

    }

}


text:
package org.springframework.boot.test.autoconfigure.web.servlet.mockmvc;

import java.util.HashMap;
import java.util.Map;

import org.springframework.hateoas.EntityModel;
import org.springframework.hateoas.Link;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * {@link RestController @RestClientTest} used by
 * {@link WebMvcTestHateoasIntegrationTests}.
 *
 * @author Andy Wilkinson
 */
@RestController
@RequestMapping("/hateoas")
class HateoasController {

	@RequestMapping("/resource")
	EntityModel<Map<String, String>> resource() {
		return new EntityModel<>(new HashMap<>(), new Link("self", "https://api.example.com"));
	}

	@RequestMapping("/plain")
	Map<String, String> plain() {
		return new HashMap<>();
	}

}


text:
<?php
/**
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 * http://www.gnu.org/copyleft/gpl.html
 *
 * @file
 * @license GPL 2+
 */

/**
 * A parser that translates page titles on a foreign wiki into ForeignTitle
 * objects, with no knowledge of the namespace setup on the foreign site.
 */
class NaiveForeignTitleFactory implements ForeignTitleFactory {
	/**
	 * Creates a ForeignTitle object based on the page title, and optionally the
	 * namespace ID, of a page on a foreign wiki. These values could be, for
	 * example, the <title> and <ns> attributes found in an XML dump.
	 *
	 * Although exported XML dumps have contained a map of namespace IDs to names
	 * since MW 1.5, the importer used to completely ignore the <siteinfo> tag
	 * before MW 1.25.  It is therefore possible that custom XML dumps (i.e. not
	 * generated by Special:Export) have been created without this metadata.
	 * As a result, this code falls back to using namespace data for the local
	 * wiki (similar to buggy pre-1.25 behaviour) if $ns is not supplied.
	 *
	 * @param string $title The page title
	 * @param int|null $ns The namespace ID, or null if this data is not available
	 * @return ForeignTitle
	 */
	public function createForeignTitle( $title, $ns = null ) {
		$pieces = explode( ':', $title, 2 );

		global $wgContLang;

		/**
		 * Can we assume that the part of the page title before the colon is a
		 * namespace name?
		 *
		 * XML export schema version 0.5 and earlier (MW 1.18 and earlier) does not
		 * contain a <ns> tag, so we need to be able to handle that case.
		 *
		 * If we know the namespace ID, we assume a non-zero namespace ID means
		 * the ':' sets off a valid namespace name. If we don't know the namespace
		 * ID, we fall back to using the local wiki's namespace names to resolve
		 * this -- better than nothing, and mimics the old crappy behavior
		 */
		$isNamespacePartValid = is_null( $ns ) ?
			( $wgContLang->getNsIndex( $pieces[0] ) !== false ) :
			$ns != 0;

		if ( count( $pieces ) === 2 && $isNamespacePartValid ) {
			list( $namespaceName, $pageName ) = $pieces;
		} else {
			$namespaceName = '';
			$pageName = $title;
		}

		return new ForeignTitle( $ns, $namespaceName, $pageName );
	}
}


text:
\AtBeginSection[]
{
  \frame
  {
    \frametitle{Contents}
    \tableofcontents[currentsection,hideallsubsections]
  }
}

\AtBeginSubsection[]
{
  \frame
  {
    \frametitle{Contents}
    \tableofcontents[sectionstyle=show/hide,subsectionstyle=show/shaded/hide]
  }
}


text:
import { IDbUser } from '../bib/user';
export interface ISession {
  User: IDbUser
}


text:
<?php

namespace PM\Tests\Unit\Main\Commander;

use PM\Main\Abstracts\Unit\TestCase;
use PM\Main\Commander\Result;
use PM\Main\Commander\Execution;

/**
 * This script defines class for php unit test case of class \PM\Main\Commander\Execution.
 *
 * @author     Martin Kovar
 * @category   Performance
 * @package    Tests
 */
class ExecutionTest  extends TestCase {

    /**
     * Success test for method execute with closure function.
     *
     * @return void
     */
    public function testClosure() {
        $execution = new Execution(function(Result $entity, $data, $const = 100) {
            $entity->setResult(5);
            return array('data' => $const);
        });

        $result = new Result();
        $execution->execute($result, $this->getProvider());
        $expected = array(
            'result' => 5,
            'data'   => 100
        );

        $this->assertInstanceOf('PM\Main\Commander\Result', $result);
        $this->assertEquals($expected, $result->toArray());
    }

    /**
     * Success test for method execute with defined scope (class) and method.
     *
     * @return void
     */
    public function testClass() {
        $class     = new TestingClass();
        $execution = new Execution('test', $class);

        $result = new Result();
        $execution->execute($result, $this->getProvider());
        $expected = array(
            'data'  => null,
            'mul'   => 200,
            'const' => 100
        );

        $this->assertInstanceOf('PM\Main\Commander\Result', $result);
        $this->assertEquals($expected, $result->toArray());
    }
}


text:
<?php
declare(strict_types=1);

namespace Lcobucci\JWT;

use Lcobucci\JWT\Encoding\CannotDecodeContent;

interface Decoder
{
    /**
     * Decodes from JSON, validating the errors
     *
     * @param non-empty-string $json
     *
     * @throws CannotDecodeContent When something goes wrong while decoding.
     */
    public function jsonDecode(string $json): mixed;

    /**
     * Decodes from Base64URL
     *
     * @link http://tools.ietf.org/html/rfc4648#section-5
     *
     * @return ($data is non-empty-string ? non-empty-string : string)
     *
     * @throws CannotDecodeContent When something goes wrong while decoding.
     */
    public function base64UrlDecode(string $data): string;
}