text:
require_relative "../../shared/controller_base"
require_relative "../../services/user_service"
require_relative "../../services/dot_keys_variable_service"
require_relative "../../shared/models/github_provider_credential"

require "octokit"

module FastlaneCI
  # Displays CI login, user creation, as well as linking github api tokens, and logging out
  class LoginController < ControllerBase
    HOME = "/login_erb"

    get HOME do
      user = session[:user]

      # Are we logged into fastlane.ci?
      if user.nil?
        # nope, redirect to login to fastlane.com
        logger.debug("No fastlane.ci account found, redirecting to login")
        redirect("/login_erb/ci_login")
      end

      # Cool, we're logged in, but have we setup a provider?
      if user_has_valid_github_token?(provider_credentials: user.provider_credentials)
        # Yup, we setup a provider, so let's go to the dashboard
        redirect("/dashboard_erb")
      end

      # Oh, no valid github provider? That's ok, let's add a github credential
      locals = {
        title: "Connect fastlane.ci with GitHub"
      }
      erb(:login, locals: locals, layout: FastlaneCI.default_layout)
    end

    # Login with fastlane.ci credentials
    get "#{HOME}/ci_login" do
      client = Octokit::Client.new(access_token: FastlaneCI.dot_keys.ci_user_api_token)

      unless client.nil?
        email = client.emails.find(&:primary).email
      end
      locals = {
        title: "Login with your fastlane.ci account",
        email: email || ""
      }

      erb(:login_fastlane_ci, locals: locals, layout: FastlaneCI.default_layout)
    end

    get "/logout" do
      session[:user] = nil

      locals = {
        title: "You are now logged out. You can log back in with your fastlane.ci account"
      }

      erb(:login_fastlane_ci, locals: locals, layout: FastlaneCI.default_layout)
    end

    # CI login
    post "/login_erb" do
      email = params[:email]
      password = params[:password]
      user = Services.user_service.login(email: email, password: password)
      if user.nil?
        redirect("#{HOME}/ci_login")
      else
        session[:user] = user
        if user_has_valid_github_token?(provider_credentials: user.provider_credentials)
          redirect("/dashboard_erb")
        else
          redirect("/login_erb")
        end
      end
    end

    get "#{HOME}/create_account" do
      locals = { title: "Create fastlane.ci account", create_failed: false }
      erb(:create_account, locals: locals, layout: FastlaneCI.default_layout)
    end

    post "#{HOME}/create_account" do
      email = params[:email]
      password = params[:password]
      user = Services.user_service.create_user!(email: email, password: password)
      if user.nil?
        locals = { title: "Create fastlane.ci account", create_failed: true }
        erb(:create_account, locals: locals, layout: FastlaneCI.default_layout)
      end
      session[:user] = user
      redirect("/login_erb")
    end

    # Submit an email and api token
    post "/login_erb/submit" do
      # check if we already have an account like this, if we do we might need to clean out their old
      # :personal_access_token
      email = params[:email]
      personal_access_token = params[:personal_access_token]
      github_provider_credential = FastlaneCI::GitHubProviderCredential.new(
        email: email,
        api_token: personal_access_token
      )
      user = session[:user]

      if user
        # needs github_provider_credential?
        needs_github_provider_credential = true
        updated_user = false
        provider_credentials = user.provider_credentials
        provider_credentials ||= []
        provider_credentials.each do |provider_credential|
          next unless provider_credential.type == FastlaneCI::ProviderCredential::PROVIDER_CREDENTIAL_TYPES[:github]
          if provider_credential.api_token.nil?
            # update out sample data
            provider_credential.api_token = github_provider_credential.api_token
            provider_credential.email = github_provider_credential.email
          end
          needs_github_provider_credential = false
          updated_user = true
        end

        if needs_github_provider_credential
          logger.debug("Account #{github_provider_credential.email} needs updating")
          provider_credentials << github_provider_credential
          user.provider_credentials = provider_credentials
          updated_user = true
        end

        Services.user_service.update_user!(user: user) if updated_user

        # Reload the user because https://github.com/fastlane/ci/issues/292
        user = Services.user_service.find_user(id: user.id)

        # update session user
        session[:user] = user
      end

      # not a big deal right now, but we should have a way of automatically generating the correct
      # CodeHostingService subclass based on the provider_credential type.
      git_hub_service = FastlaneCI::GitHubService.new(provider_credential: github_provider_credential)

      if git_hub_service.session_valid?
        redirect("/dashboard_erb")
      else
        redirect("/login_erb")
      end
    end

    def user_has_valid_github_token?(provider_credentials: [])
      provider_credentials.each do |provider_credential|
        if provider_credential.type == FastlaneCI::ProviderCredential::PROVIDER_CREDENTIAL_TYPES[:github]
          if provider_credential.api_token.nil?
            return false
          else
            return true
          end
        end
      end
      return false
    end
  end
end


text:
\documentclass{article}

\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{tikz}
\usetikzlibrary{shapes, positioning, arrows, calc}
\usetikzlibrary{decorations.pathreplacing}

\begin{document}

% Exemple tri

% 1ère étape : diviser

\begin{tikzpicture}
   \node [font=\sffamily\Large\bfseries, draw, anchor=center] (first) {$5$};
   \node [font=\sffamily\Large\bfseries, draw, anchor=center, right=0cm of first] (second) {$1$};
   \node [font=\sffamily\Large\bfseries, draw, anchor=center, right=0cm of second] (third) {$3$};
   \node [font=\sffamily\Large\bfseries, draw, anchor=center, right=0cm of third] (fourth) {$8$};
   \node [font=\sffamily\Large\bfseries, draw, anchor=center, right=0cm of fourth] (fifth) {$9$};
   \node [font=\sffamily\Large\bfseries, draw, anchor=center, right=0cm of fifth] (sixth) {$6$};
\end{tikzpicture}

\vspace{0.25cm}

\begin{tikzpicture}
   \node [font=\sffamily\Large\bfseries, draw, anchor=center] (first) {$5$};
   \node [font=\sffamily\Large\bfseries, draw, anchor=center, right=0cm of first] (second) {$1$};
   \node [font=\sffamily\Large\bfseries, draw, anchor=center, right=0cm of second] (third) {$3$};
\end{tikzpicture}
\hspace{0.1cm}
\begin{tikzpicture}
   \node [font=\sffamily\Large\bfseries, draw, anchor=center] (first) {$8$};
   \node [font=\sffamily\Large\bfseries, draw, anchor=center, right=0cm of first] (second) {$9$};
   \node [font=\sffamily\Large\bfseries, draw, anchor=center, right=0cm of second] (third) {$6$};
\end{tikzpicture}

\vspace{0.25cm}

\begin{tikzpicture}
   \node [font=\sffamily\Large\bfseries, draw, anchor=center] (first) {$5$};
\end{tikzpicture}
\hspace{0.1cm}
\begin{tikzpicture}
   \node [font=\sffamily\Large\bfseries, draw, anchor=center] (first) {$1$};
   \node [font=\sffamily\Large\bfseries, draw, anchor=center, right=0cm of first] (second) {$3$};
\end{tikzpicture}
\hspace{0.1cm}
\begin{tikzpicture}
   \node [font=\sffamily\Large\bfseries, draw, anchor=center] (first) {$8$};
\end{tikzpicture}
\hspace{0.1cm}
\begin{tikzpicture}
   \node [font=\sffamily\Large\bfseries, draw, anchor=center] (first) {$9$};
   \node [font=\sffamily\Large\bfseries, draw, anchor=center, right=0cm of first] (second) {$6$};
\end{tikzpicture}

\vspace{0.25cm}

\begin{tikzpicture}
   \node [fill=blue!20, font=\sffamily\Large\bfseries, draw, anchor=center] (first) {$5$};
\end{tikzpicture}
\hspace{0.1cm}
\begin{tikzpicture}
   \node [fill=blue!20, font=\sffamily\Large\bfseries, draw, anchor=center] (first) {$1$};
\end{tikzpicture}
\hspace{0.1cm}
\begin{tikzpicture}
   \node [fill=blue!20, font=\sffamily\Large\bfseries, draw, anchor=center] (first) {$3$};
\end{tikzpicture}
\hspace{0.1cm}
\begin{tikzpicture}
   \node [fill=blue!20, font=\sffamily\Large\bfseries, draw, anchor=center] (first) {$8$};
\end{tikzpicture}
\hspace{0.1cm}
\begin{tikzpicture}
   \node [fill=blue!20, font=\sffamily\Large\bfseries, draw, anchor=center] (first) {$9$};
\end{tikzpicture}
\hspace{0.1cm}
\begin{tikzpicture}
   \node [fill=blue!20, font=\sffamily\Large\bfseries, draw, anchor=center] (first) {$6$};
\end{tikzpicture}
\hspace{0.1cm}

% 2ème étape : fusionner

\vspace{1cm}

\begin{tikzpicture}
   \node [font=\sffamily\Large\bfseries, draw, anchor=center] (first) {$1$};
   \node [font=\sffamily\Large\bfseries, draw, anchor=center, right=0cm of first] (second) {$5$};
\end{tikzpicture}
\hspace{0.1cm}
\begin{tikzpicture}
   \node [font=\sffamily\Large\bfseries, draw, anchor=center] (first) {$3$};
   \node [font=\sffamily\Large\bfseries, draw, anchor=center, right=0cm of first] (second) {$8$};
\end{tikzpicture}
\hspace{0.1cm}
\begin{tikzpicture}
   \node [font=\sffamily\Large\bfseries, draw, anchor=center] (first) {$6$};
   \node [font=\sffamily\Large\bfseries, draw, anchor=center, right=0cm of first] (second) {$9$};
\end{tikzpicture}
\hspace{0.1cm}

\vspace{0.25cm}

\begin{tikzpicture}
   \node [font=\sffamily\Large\bfseries, draw, anchor=center] (first) {$1$};
   \node [font=\sffamily\Large\bfseries, draw, anchor=center, right=0cm of first] (second) {$3$};
   \node [font=\sffamily\Large\bfseries, draw, anchor=center, right=0cm of second] (third) {$5$};
   \node [font=\sffamily\Large\bfseries, draw, anchor=center, right=0cm of third] (fourth) {$8$};
\end{tikzpicture}
\hspace{0.1cm}
\begin{tikzpicture}
   \node [font=\sffamily\Large\bfseries, draw, anchor=center] (first) {$6$};
   \node [font=\sffamily\Large\bfseries, draw, anchor=center, right=0cm of first] (second) {$9$};
\end{tikzpicture}
\hspace{0.1cm}

\vspace{0.25cm}

\begin{tikzpicture}
   \node [fill=green!20, font=\sffamily\Large\bfseries, draw, anchor=center] (first) {$1$};
   \node [fill=green!20, font=\sffamily\Large\bfseries, draw, anchor=center, right=0cm of first] (second) {$3$};
   \node [fill=green!20, font=\sffamily\Large\bfseries, draw, anchor=center, right=0cm of second] (third) {$5$};
   \node [fill=green!20, font=\sffamily\Large\bfseries, draw, anchor=center, right=0cm of third] (fourth) {$6$};
   \node [fill=green!20, font=\sffamily\Large\bfseries, draw, anchor=center, right=0cm of fourth] (fifth) {$8$};
   \node [fill=green!20, font=\sffamily\Large\bfseries, draw, anchor=center, right=0cm of fifth] (sixth) {$9$};
\end{tikzpicture}

\end{document}

redpajama_set_name: RedPajamaGithub


text:
        <textarea class="form-control" id="chat-comment" name="comment" placeholder="Input comment"></textarea>

          <button id="chat-comment-submit" class="btn btn-primary" type="button">

            Comment
          </button>

         {% for comment in comments %}

                {{ comment.user }}
                {{ comment.created_at }}

{{comment.text}}

         {% endfor %}


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

    <string name="app_name">P2DPager</string>
    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>
    <string name="action_show">Show</string>
</resources>


text:
<tool id="pyega3" name="EGA Download Client" version="@VERSION@+galaxy0" profile="19.09" >
    <macros>
        <token name="@VERSION@">3.4.0</token>
    </macros>
    <requirements>
        <requirement type="package" version="@VERSION@">pyega3</requirement>
    </requirements>
        <command detect_errors="exit_code"><![CDATA[
#set $username = $__user__.extra_preferences.get('ega_account|username', "")
#if $username == "":
    #set $username = "ega-test-data@ebi.ac.uk (default user)"
#end if
    echo "Running as user: $username. Set your credentials via: User -> Preferences -> Manage Information"  &&

#if $action.action_type == "list_datasets"
    pyega3 -cf '$credentials'
      datasets
#elif $action.action_type == "list_dataset_files"
    pyega3 -cf '$credentials'
      files '$action.dataset_id'
#elif $action.action_type == "download_file"
    pyega3 -cf '$credentials'
      fetch '$action.file_id'
      #if $action.range.reference_name
        --reference-name '$action.range.reference_name'
        #if $action.range.start
          --start $action.range.start
        #end if
        #if $action.range.end
          --end $action.range.end
        #end if
      #end if
      --saveto '$downloaded_file'
#end if
    ]]></command>
    <configfiles>
        <configfile name="credentials"><![CDATA[
#set $password = $__user__.extra_preferences.get('ega_account|password', "")
#set $username = $__user__.extra_preferences.get('ega_account|username', "")
#if $username == "" or $password == "":
   #set $username = "ega-test-data@ebi.ac.uk"
   #set $password = "egarocks"
#end if
{
    "username": "$username",
    "password": "$password"
}
        ]]></configfile>
    </configfiles>
    <inputs>
        <conditional name="action">
            <param name="action_type" type="select" label="What would you like to do?">
                <option value="list_datasets"> List my authorized datasets </option>
                <option value="list_dataset_files"> List files in a datasets </option>
                <option value="download_file"> Download a file </option>
            </param>
            <when value="list_dataset_files">
                <param name="dataset_id" type="text" optional="false" label="EGA Dataset Accession ID" help="Identifier starting with 'EGAD'. For example: EGAD00001003338">
                    <validator type="regex" message="EGA dataset ID must be a string of numbers prefixed by 'EGAD'">EGAD[0-9]+</validator>
                </param>
            </when>
            <when value="list_datasets"/>
            <when value="download_file">
                <param name="file_id" type="text" optional="false" label="EGA File Accession Identifier" help="Identifier starting with 'EGAF'. For example: EGAF00001753735">
                     <validator type="regex" message="EGA Accession ID must be a string of numbers prefixed by 'EGAD' (datasets) or 'EGAF' (files)">EGAF[0-9]+</validator>
                </param>
                <section name="range" title="Request a specific Genomic range?" expanded="false">
                <param argument="--reference-name" type="text" optional="true" label="Reference Sequence Name" help="For example 'chr1', '1', or 'chrX'. If unspecified, all data is returned." />
                <param argument="--start" type="integer" optional="true" min="0" label="Start Position" help="0-based, inclusive. Only used if a reference sequence name was specified"/>
                <param argument="--end" type="integer" optional="true" min="0" label="End Position" help="0-based, exclusive. Only used if a reference sequence name was specified"/>
                </section>
            </when>
        </conditional>
    </inputs>
    <outputs>
        <data name="authorized_datasets" format="txt" from_work_dir="pyega3_output.log" label="${tool.name}: authorized datasets">
            <filter> action['action_type'] == 'list_datasets' </filter>
        </data>
        <data name="dataset_file_list" format="txt" from_work_dir="pyega3_output.log" label="${tool.name}: dataset file list">
            <filter> action['action_type'] == 'list_dataset_files' </filter>
        </data>
        <data name="downloaded_file" auto_format="true" label="${tool.name}: ${action.file_id} ${action.range.reference_name} ${action.range.start} ${action.range.end}">
            <filter> action['action_type'] == 'download_file' </filter>
        </data>
    </outputs>
    <tests>
        <test expect_num_outputs="1"><!-- list datasets with default credentials -->
            <param name="action_type" value="list_datasets"/>
            <output name="authorized_datasets" ftype="txt">
                <assert_contents>
                    <has_text text="pyEGA3 - EGA python client version @VERSION@"/>
                    <has_text text="EGAD00001003338"/>
                </assert_contents>
            </output>
        </test>
        <test expect_num_outputs="1"><!-- list dataset files with default credentials -->
            <param name="action_type" value="list_dataset_files"/>
            <param name="dataset_id" value="EGAD00001003338"/>
            <output name="dataset_file_list" ftype="txt">
                <assert_contents>
                    <has_text text="pyEGA3 - EGA python client version @VERSION@"/>
                    <has_line_matching expression="^\[.*\]\s+File ID\s+Status\s+Bytes\s+Check sum\s+File name$"/>
                    <has_text text="EGAF00001753734"/>
                </assert_contents>
            </output>
        </test>
        <test expect_num_outputs="1"> <!-- download a single file -->
            <param name="action_type" value="download_file"/>
            <param name="file_id" value="EGAF00001775036"/>
            <output name="downloaded_file" md5="3b89b96387db5199fef6ba613f70e27c"/>
        </test>
         <test expect_num_outputs="1"> <!-- download a single file, with genomic range specified -->
            <param name="action_type" value="download_file"/>
            <param name="file_id" value="EGAF00001753756"/>
            <param name="reference_name" value="1"/>
            <param name="start" value="100"/>
            <param name="end" value="10000"/>
            <output name="downloaded_file" ftype="bam" md5="e576a38748feec45aa45191f6e902ce2"/>
        </test>
    </tests>
    <help><![CDATA[
The pyEGA3 download client is a python-based tool for viewing and downloading files from authorized EGA datasets.

If you have an EGA account, you can set your EGA credentials in the user preferences menu of Galaxy. Otherwise, default EGA credentials with access to an example dataset will be used.

pyEGA3 uses the EGA Data API and has several key features:

- Files are transferred over secure https connections and received unencrypted, so no need for decryption after download.
- Downloads resume from where they left off in the event that the connection is interrupted.
- pyEGA3 supports file segmenting and parallelized download of segments, improving overall performance.
- After download completes, file integrity is verified using checksums.
- pyEGA3 implements the GA4GH-compliant htsget protocol for download of genomic ranges for data files with accompanying index files.

    ]]></help>
    <citations>
        <citation type="doi">10.1038/ng.3312</citation>
    </citations>
</tool>


text:
package cc.apoc.rccvm;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;

import cc.apoc.rccvm.qemu.VirtualMachine;

import com.google.gson.Gson;

public class Config {
    String web_bind_host;
    int web_bind_port;
    public boolean bypass_task_queue;
    int client_timeout;
    VirtualMachine.Config vm;

    public static Config read(String filename) {
        try {
            Gson gson = new Gson();
            BufferedReader reader = new BufferedReader(new FileReader(filename));
            return gson.fromJson(reader, Config.class);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }

}


text:
package com.springboot.spark.starter.basic.rdd;

import java.io.Serializable;
import java.util.Arrays;
import java.util.concurrent.ExecutionException;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaFutureAction;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.VoidFunction;

/**
 *
 */
public class JavaRDDforeach implements Serializable {

  private static final long serialVersionUID = 5924321403879655951L;

  private final static SparkConf sparkConf = new SparkConf() //
      .setAppName(JavaRDDforeach.class.getName()) //
      .setMaster("local") //
  ; //

  public final static JavaSparkContext sc = new JavaSparkContext(sparkConf);

  public void using() throws InterruptedException, ExecutionException {
    JavaRDD<Integer> rdd1 = sc.parallelize(Arrays.asList(1, 2, 3, 4, 5, 3, 5));
    rdd1.foreach(new VoidFunction<Integer>() {
      private static final long serialVersionUID = -3596600139708805107L;

      @Override
      public void call(Integer t) throws Exception {
        System.err.print("元素:" + t + ",");
      }
    });
    // 输出
    // 元素:1,元素:2,元素:3,元素:4,元素:5,元素:3,元素:5,
    JavaFutureAction<Void> foreachAsync = rdd1.foreachAsync(new VoidFunction<Integer>() {
      private static final long serialVersionUID = -8449909925571012215L;

      @Override
      public void call(Integer t) throws Exception {
        System.err.print("元素:" + t + "|");
      }
    });
    long start = System.currentTimeMillis();
    // Waits if necessary for the computation to complete, and then retrieves its result.
    foreachAsync.get();
    System.err.println("计算完成,耗时:" + (System.currentTimeMillis() - start) + "ms");
    // 计算完成,耗时:23ms
  }

  public static void main(String[] args) throws Exception {
    new JavaRDDforeach().using();
    sc.close();
  }

}


text:
WorldPlayerCounter    g_WorldPlayerCounter ;
TurnPlayerQueue*      g_pProcessPlayerQueue = NULL ;
WorldPlayerQueue*     g_pWorldPlayerQueue = NULL ;

TurnPlayerQueue::TurnPlayerQueue()
{
    __ENTER_FUNCTION

        m_Size                = MAX_TURN_PLAYER ;
        m_pTurnPlayerQueue    = new TURN_PLAYER_INFO[ m_Size ] ;
        m_Head    = 0 ;
        m_Tail    = 0 ;

    __LEAVE_FUNCTION
}

TurnPlayerQueue::~TurnPlayerQueue()
{
    __ENTER_FUNCTION

        SAFE_DELETE_ARRAY( m_pTurnPlayerQueue ) ;

    __LEAVE_FUNCTION
}

BOOL TurnPlayerQueue::Init()
{
    return TRUE ;
}

BOOL TurnPlayerQueue::AddInPlayer( PlayerID_t pID, const CHAR* Name, UINT& QueuePos )
{

    __ENTER_FUNCTION

        AutoLock_T autolock( m_Lock ) ;

        if ( m_pTurnPlayerQueue[ m_Tail ].Used )
        {//队列满
            return FALSE ;
        }

        m_pTurnPlayerQueue[ m_Tail ].Used        = TRUE ;
        m_pTurnPlayerQueue[ m_Tail ].PlayerID    = pID ;

        strncpy( m_pTurnPlayerQueue[ m_Tail ].PlayerName, Name, MAX_ACCOUNT ) ;
        m_pTurnPlayerQueue[ m_Tail ].PlayerName[ MAX_ACCOUNT ] = '\0' ;
        m_pTurnPlayerQueue[ m_Tail ].QueuePos = m_Tail;

        QueuePos = m_Tail ;

        m_Tail++ ;
        if ( m_Tail >= m_Size ) m_Tail = 0 ;

        return TRUE ;

    __LEAVE_FUNCTION

        return FALSE ;
}

BOOL TurnPlayerQueue::GetOutPlayer( PlayerID_t& pID, CHAR* NameBuff )
{
    __ENTER_FUNCTION

        AutoLock_T autolock( m_Lock ) ;

        if ( FALSE == m_pTurnPlayerQueue[ m_Head ].Used )
        {//没有队列玩家
            return FALSE ;
        }

        Assert( NameBuff ) ;
        strncpy( NameBuff,m_pTurnPlayerQueue[ m_Head ].PlayerName, MAX_ACCOUNT ) ;
        NameBuff[ MAX_ACCOUNT ] = '\0' ;

        pID = m_pTurnPlayerQueue[ m_Head ].PlayerID ;

        m_pTurnPlayerQueue[ m_Head ].Used = FALSE ;

        m_Head++ ;
        if ( m_Head >= m_Size ) m_Head = 0 ;

        return TRUE ;

    __LEAVE_FUNCTION

        return FALSE ;
}

WorldPlayerQueue::WorldPlayerQueue()
{
    __ENTER_FUNCTION

        m_Size                =    MAX_WORLDTURN_PLAYER ;
        m_pWorldPlayerQueue   =    new WORLD_PLAYER_INFO[ m_Size ] ;

        m_Head = 0 ;
        m_Tail = 0 ;

    __LEAVE_FUNCTION
}

WorldPlayerQueue::~WorldPlayerQueue()
{
    __ENTER_FUNCTION

        SAFE_DELETE_ARRAY( m_pWorldPlayerQueue ) ;

    __LEAVE_FUNCTION
}

BOOL WorldPlayerQueue::Init()
{
    return TRUE ;
}

BOOL WorldPlayerQueue::AddInPlayer( PlayerID_t pID, const CHAR* Name, GUID_t guid, BYTE age, UINT& QueuePos )
{
    __ENTER_FUNCTION

        AutoLock_T autolock( m_Lock ) ;

        if ( m_pWorldPlayerQueue[ m_Tail ].Used )
        {//队列满
            return FALSE ;
        }

        m_pWorldPlayerQueue[ m_Tail ].Used        = TRUE ;
        m_pWorldPlayerQueue[ m_Tail ].PlayerID    = pID ;

        strncpy( m_pWorldPlayerQueue[ m_Tail ].PlayerName, Name, MAX_ACCOUNT ) ;
        m_pWorldPlayerQueue[ m_Tail ].PlayerName[ MAX_ACCOUNT ] = '\0';
        m_pWorldPlayerQueue[ m_Tail ].QueuePos        = m_Tail ;
        m_pWorldPlayerQueue[ m_Tail ].Guid            = guid ;
        m_pWorldPlayerQueue[ m_Tail ].Age             = age ;

        QueuePos = m_Tail ;

        m_Tail++ ;
        if ( m_Tail >= m_Size ) m_Tail = 0 ;

        return TRUE;

    __LEAVE_FUNCTION

        return FALSE;
}

BOOL WorldPlayerQueue::GetOutPlayer( UINT QueuePos )
{
    __ENTER_FUNCTION

        AutoLock_T autolock( m_Lock ) ;

        if ( FALSE == m_pWorldPlayerQueue[ m_Head ].Used )
        {//没有队列玩家
            return FALSE ;
        }
        Assert( QueuePos == m_Head ) ;

        m_pWorldPlayerQueue[ m_Head ].Used = FALSE ;

        m_Head++ ;
        if ( m_Head >= m_Size ) m_Head = 0 ;

        return TRUE ;

    __LEAVE_FUNCTION

        return FALSE ;
}

BOOL WorldPlayerQueue::FindHeadPlayer( UINT& QueuePos )
{
    __ENTER_FUNCTION

        AutoLock_T autolock( m_Lock ) ;

        if ( FALSE == m_pWorldPlayerQueue[ m_Head ].Used )
        {//没有队列玩家
            return FALSE ;
        }
        QueuePos = m_Head ;

        return TRUE ;

    __LEAVE_FUNCTION

        return FALSE ;
}

WORLD_PLAYER_INFO& WorldPlayerQueue::GetPlayer( UINT QueuePos )
{
    return m_pWorldPlayerQueue[ QueuePos ] ;
}


text:
/*
 * GenomeSelectionDialog.java
 *
 * Created on November 8, 2007, 3:51 PM
 */

package org.broad.igv.ui;

import javax.swing.*;

/**
 * @author eflakes
 */
public class AttributeSelectionDialog extends javax.swing.JDialog {

    private boolean isCanceled = true;

    /**
     * Creates new form GenomeSelectionDialog
     */
    public AttributeSelectionDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        setLocationRelativeTo(parent);
    }

    public void setModel(ComboBoxModel model) {
        comboBox.setModel(model);
    }

    public void setSelectedItem(Object selection) {
        comboBox.setSelectedItem(selection);
    }

    public void setSelectedIndex(int index) {
        comboBox.setSelectedIndex(index);
    }

    public int getSelectedIndex() {
        return comboBox.getSelectedIndex();
    }

    public boolean isCanceled() {
        return isCanceled;
    }

    /**
     * This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        comboBox = new JComboBox();
        genomeComboBoxLabel = new javax.swing.JLabel();
        okButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Group By Attribute");
        setResizable(false);

        comboBox.setEditable(false);

        genomeComboBoxLabel.setText("Group tracks by:");

        okButton.setText("Ok");
        okButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                okButtonActionPerformed(evt);
            }
        });

        cancelButton.setText("Cancel");
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                        .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                                .addContainerGap()
                                .add(genomeComboBoxLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 112, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                                .add(comboBox, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 318, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                .addContainerGap())
                        .add(layout.createSequentialGroup()
                                .add(145, 145, 145)
                                .add(okButton)
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                .add(cancelButton)
                                .addContainerGap(183, Short.MAX_VALUE))
        );

        layout.linkSize(new java.awt.Component[]{cancelButton, okButton}, org.jdesktop.layout.GroupLayout.HORIZONTAL);

        layout.setVerticalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                        .add(layout.createSequentialGroup()
                                .add(50, 50, 50)
                                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                                        .add(genomeComboBoxLabel)
                                        .add(comboBox, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                                .add(18, 18, 18)
                                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                                        .add(okButton)
                                        .add(cancelButton))
                                .addContainerGap())
        );

        layout.linkSize(new java.awt.Component[]{cancelButton, okButton}, org.jdesktop.layout.GroupLayout.VERTICAL);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        isCanceled = true;
        setVisible(false);
        dispose();
    }//GEN-LAST:event_cancelButtonActionPerformed

    private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed
        isCanceled = false;
        setVisible(false);
        dispose();
    }//GEN-LAST:event_okButtonActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new AttributeSelectionDialog(new javax.swing.JFrame(), true).setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cancelButton;
    JComboBox comboBox;
    private javax.swing.JLabel genomeComboBoxLabel;
    private javax.swing.JButton okButton;
    // End of variables declaration//GEN-END:variables

}


text:
// ´úÂëÕûÀí£ºÀÁÈËÖ®¼Ò  www.lanrenzhijia.com
$(document).ready(function(){

	/* This code is executed on the document ready event */

	var left	= 0,
		top		= 0,
		sizes	= { retina: { width:190, height:190 }, webpage:{ width:500, height:283 } },
		webpage	= $('#webpage'),
		offset	= { left: webpage.offset().left, top: webpage.offset().top },
		retina	= $('#retina');

	if(navigator.userAgent.indexOf('Chrome')!=-1)
	{
		/*	Applying a special chrome curosor,
			as it fails to render completely blank curosrs. */

		retina.addClass('chrome');
	}

	webpage.mousemove(function(e){

		left = (e.pageX-offset.left);
		top = (e.pageY-offset.top);

		if(retina.is(':not(:animated):hidden')){
			/* Fixes a bug where the retina div is not shown */
			webpage.trigger('mouseenter');
		}

		if(left<0 || top<0 || left > sizes.webpage.width || top > sizes.webpage.height)
		{
			/*	If we are out of the bondaries of the
				webpage screenshot, hide the retina div */

			if(!retina.is(':animated')){
				webpage.trigger('mouseleave');
			}
			return false;
		}

		/*	Moving the retina div with the mouse
			(and scrolling the background) */

		retina.css({
			left				: left - sizes.retina.width/2,
			top					: top - sizes.retina.height/2,
			backgroundPosition	: '-'+(1.6*left)+'px -'+(1.35*top)+'px'
		});

	}).mouseleave(function(){
		retina.stop(true,true).fadeOut('fast');
	}).mouseenter(function(){
		retina.stop(true,true).fadeIn('fast');
	});
});


text:
package com.testpoke.core.schedule;

import android.os.Handler;
import android.os.Message;

/*
 * Created by Jansel Valentin on 5/5/14.
 */
final class SchedulerHandler extends Handler {

    private SchedulerService scheduler;
    public SchedulerHandler( SchedulerService scheduler ){
        this.scheduler = scheduler;
    }

    @Override
    public void handleMessage(Message msg) {
        if (this != msg.getTarget() || !(msg.obj instanceof Task))
            return;

        final Task task = (Task) msg.obj;
        task.run();

        if (task instanceof Recurrent) {
            Recurrent rTask = (Recurrent) task;
            long recurrent = rTask.getRecurrentInterval();
            recurrent = recurrent > 0 ? recurrent : 0;

            if (0 < recurrent) {

                if( task instanceof AutoDrivenTask){
                    postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            scheduler.schedule( (AutoDrivenTask)task );
                        }
                    }, recurrent );
                }else{
                    Message rMsg = obtainMessage(task.getId(), task);
                    sendMessageDelayed(rMsg, recurrent);
                }
            }
        }
    }
}


text:
layout: documentation
title: Updating Bazel
---

# Updating Bazel

The Bazel project has a [backwards compatibility
policy](https://docs.bazel.build/versions/master/backward-compatibility.html)
(see [guidance for rolling out incompatible
changes](https://www.bazel.build/breaking-changes-guide.html) if you are the
author of one). That page summarizes best practices on how to test and migrate
your project with upcoming incompatible changes and how to provide feedback to
the incompatible change authors.

## Managing Bazel versions with Bazelisk

The Bazel team implemented a Bazel wrapper called
[bazelisk](https://github.com/bazelbuild/bazelisk) that helps you manage Bazel
versions.

Bazelisk can:
*   Auto-update Bazel to the latest version
*   Build the project with a Bazel version specified in the .bazelversion
    file. Check in that file into your version control to ensure reproducibility
    of your builds.
*   Help migrate your project for incompatible changes (see above)
*   Easily try release candidates

## Recommended migration process

Bazel backwards compatibility policy is designed to avoid _upgrade cliffs_: any
project can be prepared for the next Bazel release without breaking
compatibility with the current release.

We recommend the following process for project migration:

1. Assume that your project already works with a given Bazel release, say 0.26,
   and you want to prepare for the next release, say 0.27
2. Find all incompatible changes for which the migration can be started: they are marked with
   "migration-\<release\>" label on GitHub, for example
   "[migration-0.26](https://github.com/bazelbuild/bazel/issues?utf8=%E2%9C%93&q=label%3Amigration-0.26+)".
3. Each of those issues has an associated `--incompatible_*` flag. For each of
   them, build your project with that flag enabled, and if the build is
   unsuccessful, fix the project according to [migration
   recipe](https://docs.bazel.build/versions/master/backward-compatibility.html#incompatible-changes-and-migration-recipes)
   as specified in the corresponding GitHub issue:
    *   Migration guidance is available in the associated GitHub issue.
    *   Migration is always possible in such a way that the project continues to build with and without the flag.
    *   For some of the incompatible changes migration tooling is available, for
        example as part of
        [buildifier](https://github.com/bazelbuild/buildtools/releases). Be sure
        to check the GitHub issue for migration instructions.
    *   Please report any migration problems by commenting associated GitHub issue.
4. After all changes are migrated, you can continue to build your project
   without any flags: it will be ready for the next Bazel release.

### Migrating with Bazelisk

[Bazelisk](https://github.com/bazelbuild/bazelisk) can
greatly simplify the migration process described above.

*   `bazelisk --strict` will build given targets with all incompatible flags for
     changes with appropriate migration-* labels.
*   `bazelisk --migrate` will do even more: it will try every flag and report
     those for which the build was unsuccessful


text:
package com.dremio.service.flight.error.mapping;

import static org.junit.Assert.assertEquals;

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

import org.apache.arrow.flight.CallStatus;
import org.apache.arrow.flight.FlightRuntimeException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import com.dremio.common.exceptions.UserException;

/**
 * Unit tests for DremioFlightErrorMapper.
 */
@RunWith(Parameterized.class)
public class TestDremioFlightErrorMapper {
  private UserException.Builder builder;
  private CallStatus expectedCallStatus;

  @Parameterized.Parameters
  public static List<Object[]> testCases() {
    return Arrays.asList(
      new Object[] {UserException.connectionError(), CallStatus.INTERNAL},
      new Object[] {UserException.dataReadError(), CallStatus.INTERNAL},
      new Object[] {UserException.dataWriteError(), CallStatus.INTERNAL},
      new Object[] {UserException.functionError(), CallStatus.INTERNAL},
      new Object[] {UserException.parseError(), CallStatus.INVALID_ARGUMENT},
      new Object[] {UserException.permissionError(), CallStatus.UNAUTHORIZED},
      new Object[] {UserException.planError(), CallStatus.INTERNAL},
      new Object[] {UserException.resourceError(), CallStatus.UNAVAILABLE},
      new Object[] {UserException.systemError(new Exception("Test exception")), CallStatus.INTERNAL},
      new Object[] {UserException.unsupportedError(), CallStatus.INTERNAL},
      new Object[] {UserException.validationError(), CallStatus.INVALID_ARGUMENT},
      new Object[] {UserException.memoryError(), CallStatus.UNAVAILABLE},
      new Object[] {UserException.schemaChangeError(), CallStatus.INTERNAL},
      new Object[] {UserException.ioExceptionError(), CallStatus.UNAVAILABLE},
      new Object[] {UserException.concurrentModificationError(), CallStatus.UNAVAILABLE},
      new Object[] {UserException.invalidMetadataError(), CallStatus.INTERNAL},
      new Object[] {UserException.reflectionError(), CallStatus.INTERNAL},
      new Object[] {UserException.sourceInBadState(), CallStatus.INTERNAL},
      new Object[] {UserException.jsonFieldChangeError(), CallStatus.INTERNAL},
      new Object[] {UserException.resourceTimeoutError(), CallStatus.TIMED_OUT}
    );
  }

  public TestDremioFlightErrorMapper(UserException.Builder builder, CallStatus expectedCallStatus) {
    this.builder = builder;
    this.expectedCallStatus = expectedCallStatus;
  }

  @Test
  public void testDremioParseError() {
    final UserException userEx = builder.buildSilently();
    final FlightRuntimeException flightRuntimeEx =
      DremioFlightErrorMapper.toFlightRuntimeException(userEx);

    assertEquals(flightRuntimeEx.status().code(), expectedCallStatus.code());
  }
}


text:
/*
 * EIoHandlerAdapter.cpp
 *
 *  Created on: 2013-8-19
 *      Author: cxxjava@163.com
 */

#include "../inc/EIoHandlerAdapter.hh"

namespace efc {
namespace eio {

sp<ELogger> EIoHandlerAdapter::LOGGER = ELoggerManager::getLogger("EIoHandlerAdapter");

void EIoHandlerAdapter::sessionCreated(sp<EIoSession>& session) {
	// Empty handler
}

void EIoHandlerAdapter::sessionOpened(sp<EIoSession>& session) {
	// Empty handler
}

void EIoHandlerAdapter::sessionClosed(sp<EIoSession>& session) {
	// Empty handler
}

void EIoHandlerAdapter::sessionIdle(sp<EIoSession>& session, EIdleStatus status) {
	// Empty handler
}

void EIoHandlerAdapter::exceptionCaught(sp<EIoSession>& session, sp<EThrowableType>& cause) {
	EThrowable* t = cause->getThrowable();
	if (t) {
		LOGGER->warn_("EXCEPTION, please implement EIoHandlerAdapter.exceptionCaught() for proper handling:%s",
				t->getMessage());
	}
}

void EIoHandlerAdapter::messageReceived(sp<EIoSession>& session, sp<EObject>& message) {
	// Empty handler
}

void EIoHandlerAdapter::messageSent(sp<EIoSession>& session, sp<EObject>& message) {
	// Empty handler
}

void EIoHandlerAdapter::inputClosed(sp<EIoSession>& session) {
	session->closeNow();
}

} /* namespace eio */
} /* namespace efc */


text:
package org.apache.axis2.corba.receivers;

import org.apache.axis2.corba.exceptions.CorbaInvocationException;
import org.apache.axis2.corba.idl.types.DataType;
import org.apache.axis2.corba.idl.types.ExceptionType;
import org.apache.axis2.corba.idl.types.Interface;
import org.apache.axis2.corba.idl.types.Member;
import org.apache.axis2.corba.idl.types.Operation;
import org.apache.axis2.corba.idl.values.ExceptionValue;
import org.omg.CORBA.Any;
import org.omg.CORBA.ExceptionList;
import org.omg.CORBA.Request;
import org.omg.CORBA.TypeCode;
import org.omg.CORBA.UnknownUserException;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class CorbaInvoker implements Invoker {
    private Operation operation;
    private Interface intf;
    //private Map compositeDataTypes;
    private org.omg.CORBA.Object object;
    private Object[] parameters;
    private List parameterTypeList = new ArrayList();
    private List returnedParams;

    protected CorbaInvoker(Operation operation, Interface intf, org.omg.CORBA.Object object) {
        this.operation = operation;
        this.intf = intf;
        this.object = object;

        List params = operation.getParams();
        if (params!=null) {
            for (int i = 0; i < params.size(); i++) {
                Member member = (Member) params.get(i);
                parameterTypeList.add(member);
            }
        }
    }

    public Object invoke() throws CorbaInvocationException {
        // Create request
        Request request = object._request(operation.getName());

        // Set parameters
        Any arg = null;
        List memArgs = new ArrayList();
        if (parameters!=null) {
            List patamList = new LinkedList(Arrays.asList(parameters));
            Iterator paramsIter = patamList.iterator();
            for (int i = 0; i < parameterTypeList.size(); i++) {
                Member member = (Member) parameterTypeList.get(i);
                DataType type = member.getDataType();
                Object value = null;
                String mode = member.getMode();
                if (mode.equals(Member.MODE_IN)) {
                    arg = request.add_in_arg();
                    value = paramsIter.next();
                }else if (mode.equals(Member.MODE_INOUT)) {
                    arg = request.add_inout_arg();
                    value = paramsIter.next();
                } else if (mode.equals(Member.MODE_OUT)) {
                    arg = request.add_out_arg();
                    value = CorbaUtil.getEmptyValue(type);
                }

                memArgs.add(arg);
                CorbaUtil.insertValue(arg, type, value);
            }
        }

        // Set return type
        DataType returnType = operation.getReturnType();
        if (returnType!=null) {
            TypeCode typeCode = returnType.getTypeCode();
            request.set_return_type(typeCode);
        }

        // Set exceptions
        List exceptions = operation.getRaises();
        if (exceptions!=null && !exceptions.isEmpty()) {
            ExceptionList exceptionList = request.exceptions();
            for (int i = 0; i < exceptions.size(); i++) {
                ExceptionType exType = (ExceptionType) exceptions.get(i);
                exceptionList.add(exType.getTypeCode());
            }
        }

        // Invoke
        request.invoke();

        // Get exception
        Object returnValue = null;
        Exception exception = request.env().exception();
        if (exception == null) {
            // Extract the return value
            if (returnType != null) {
                Any returned = request.return_value();
                returnValue = CorbaUtil.extractValue(returnType, returned);
            }

            // Extract the values of inout and out parameters
            returnedParams = new ArrayList();
            for (int i = 0; i < parameterTypeList.size(); i++) {
                Member member = (Member) parameterTypeList.get(i);
                String mode = member.getMode();
                if (mode.equals(Member.MODE_INOUT) || mode.equals(Member.MODE_OUT)) {
                    returnedParams.add(CorbaUtil.extractValue(member.getDataType(), (Any) memArgs.get(i)));
                }
            }
        } else {
            if(exception instanceof UnknownUserException) {
                UnknownUserException userException = (UnknownUserException) exception;
                TypeCode exTypeCode = userException.except.type();
                ExceptionType exceptionType = null;
                if (exceptions!=null && !exceptions.isEmpty()) {
                    for (int i = 0; i < exceptions.size(); i++) {
                        ExceptionType exType = (ExceptionType) exceptions.get(i);
                        if (exTypeCode.equal(exType.getTypeCode())) {
                            exceptionType = exType;
                            break;
                        }
                    }
                }
                if (exceptionType==null) {
                    throw new CorbaInvocationException(exception);
                } else {
                    ExceptionValue exceptionValue = (ExceptionValue) CorbaUtil.extractValue(exceptionType, userException.except);
                    if (exceptionValue!=null)
                        throw exceptionValue.getException();
                }
            } else {
                throw new CorbaInvocationException(exception);
            }
        }

        return returnValue;
    }

    public void setParameters(Object[] parameters){
        this.parameters = parameters;
    }

    public String getInterfaceName(){
        return intf.getName();
    }

    public String getOperationName(){
        return operation.getName();
    }

    public DataType getReturnType() {
        return operation.getReturnType();
    }

    public Object[] getOutParameterValuess() {
        if (returnedParams == null)
            return null;
        else
            return returnedParams.toArray();
    }

    public Member[] getParameterMembers() {
        Member[] membersArray = new Member[parameterTypeList.size()];
        for (int i = 0; i < parameterTypeList.size(); i++) {
            membersArray[i] = (Member) parameterTypeList.get(i);
        }
        return membersArray;
    }
}


text:
    <link rel="Stylesheet" type="text/css" href="style.css" />
    <title>Travel deals</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    Home|
    Personal Todo|
    Aware Todo|
    Goals|
    Finances|
    Notes|
    Diary

Travel deals

Best Western credit

Westfir lodge credit (Oakridge)

Home exchange

Scott's flights

AAA

Groupon


text:
typedef void (*WriteDataProc)(int,BYTE *);

//  size of data going to/from the device
#define IK_REPORT_LEN 8

//  resolution of the device
#define IK_RESOLUTION_X 24
#define IK_RESOLUTION_Y 24

//  number of switches
#define IK_NUM_SWITCHES  6

//  number of sensors
#define IK_NUM_SENSORS   3

//  some internal commands that don't make it to the device
#define COMMAND_BASE 100
#define IK_CMD_DELAY				COMMAND_BASE+1 // (msec)
#define IK_CMD_MOUSE_MOVE			COMMAND_BASE+2 // (x, y)
#define IK_CMD_MOUSE_BUTTON			COMMAND_BASE+3 // (left/right, down/up)
#define IK_CMD_KEYBOARD				COMMAND_BASE+4 // (keycode, down/up)
#define IK_CMD_KEY_DONE				COMMAND_BASE+5 // signal downstream that a key is done
#define IK_CMD_KEY_START			COMMAND_BASE+6 // signal downstream that a key is starting
#define IK_CMD_KEY_REPEAT			COMMAND_BASE+7 // signal downstream that a key is repeating

#define IK_CMD_CP_HELP				COMMAND_BASE+8
#define IK_CMD_CP_LIST_FEATURES		COMMAND_BASE+9
#define IK_CMD_CP_REFRESH			COMMAND_BASE+10
#define IK_CMD_CP_TOGGLE			COMMAND_BASE+11

#define IK_CMD_KEYBOARD_UNICODE		COMMAND_BASE+12 // lead, trail, down/up

#define IK_CMD_LIFTALLMODIFIERS     COMMAND_BASE+13

#define IK_CMD_CP_REPORT_REALTIME	COMMAND_BASE+14

//  for keystrokes and mouse buttons
enum {IK_DOWN=1,IK_UP,IK_TOGGLE};
enum {IKUSB_LEFT_BUTTON=0,IKUSB_RIGHT_BUTTON,IKUSB_MIDDLE_BUTTON,IKUSB_BUTTON_4,IKUSB_BUTTON_5,IKUSB_BUTTON_6,IKUSB_BUTTON_7,IKUSB_BUTTON_8};

enum {
	kModifierStateOff = 0,
	kModifierStateLatched,
	kModifierStateLocked
};

class IKDevice
{
public:
	void KeySound2 ( int msLength, int freq );
	bool IsIntelliSwitchV1 ();
	int CountRawEvents ();
	void ShortKeySound();
	void LongKeySound();
	bool GetRawEvent ( BYTE *bytes );
	void PurgeRawQueue();
	void InterpretRaw ();
	void SetDevType (int devType) {m_devType = devType;}
	int  GetDevType () {return m_devType;}
	void Disconnect();
	int GetCurrentOverlayNumber() {return m_currentOverlay;}
	void PostReportDataToControlPanel(bool bForce=false);
	IKString GetKeyName ( int code );
	int GetRepeatDelayMS();
	void DoSetLED ( int number, int on );
	void ReportDataToControlPanel(bool bForce = false);
	void PostLiftAllModifiers();
	void KickDLL();
	void PostKeyUnicode ( BYTE lead, BYTE trail, int direction );
	void PostKeyStroke ( int code );
	void PostCPRefresh();
	IKString GetSerialNumber();
	int GetLevel();
	IKOverlay * GetCurrentOverlay();
	int GetIndex();
	void GetMembraneStatus ( BYTE *data, int *ndata );
	void GetSwitchStatus ( BYTE *data, int nswitch );
	void GetSensorArray ( BYTE *data );
	void UserReset(bool bFromCP);
	void LiftNonModifiers();
	void SetLevel(int level);
	void OverlaySendingFeedback();
	bool HasStandardOverlay();
	void SetCode ( BYTE code );
	IKDevice();
	virtual ~IKDevice();
	void Periodic ();
	void DoKey(int code, int direction);
	void DoKeyUnicode(BYTE lead, BYTE trail, int direction);
	static IKString GetCommandName ( BYTE command );
	bool IsSwitchedOn();
	void Reset();
	bool IsOpen() {return m_bOpen;}
	void SetOpen(bool bOpen) {m_bOpen = bOpen;}
	void SetIndex(int index) {m_index = index;}
	void SetWriteProc (WriteDataProc proc) {m_writeProc = proc;}
	void Start();
	void OnDataReceived ( BYTE *data );
	void PostKey(int code, int direction, int delayAfter=0);
	void KeySound(int msLength);
	void PostDelay(int ms);
	void PostMouseButtonToggle(int whichButton);
	void PostMouseButtonClick(int whichButton);
	void PostMouseButtonDoubleClick(int whichButton);
	void PostMouseButton(int whichButton, int direction);
	void PostMouseMove(int x, int y);
	void ResetMouse();
	void ResetKeyboard();

	void RawNotify ( int eventType, int i1, int i2, int time );
	// June 2012 - JR - added for retrieval of firmware version
	IKString FirmwareVersion();

private:
	bool m_bCapsLock;
	bool m_bNumLock;
	void PurgeToLastStart();
	static void SaveKeyboardSettings();
	static void RestoreKeyboardSettings();
	bool IsNumLockOn();
	bool IsCapsLockOn();
	bool IsMouseDown();
	unsigned int m_lastLEDTime;
	void SetLEDs();
	void DoKeyRepeat();
	void DoKeyStart();
	void DoKeyDone();
	void LiftAllLatchedModifiers();
	void LiftAllModifiers();
	void PostKeyDone();
	void PostKeyStart();
	void PostKeyRepeat();
	bool IsAnyModifierDown();
	bool IsMouseAction(BYTE code);
	void HackKeyContent ( BYTE *data );
	void ResetSound();
	void DeleteLastSentOverlay();
	int ComputeMouseInc(int nPar);
	bool IsIdle();
	int  CountRealCodes (BYTE *data);
	bool HasMouseClicks (BYTE *data);
	bool HasMouseActions (BYTE *data);
	bool IsModifier (BYTE data);
	bool IsMouseMove (BYTE data);
	bool IsMouseClick (BYTE data);
	bool IsSetupCode (BYTE data);
	bool HasSetupCodes (BYTE *data);
	bool HasOnlyMouseMoveActions (BYTE *data);
	bool HasNonRepeating(BYTE *data);
	bool DoSetupKey ( BYTE * data );

	//  type definition of an entry in a queue
	typedef struct
	{
		BYTE buffer[IK_REPORT_LEN];
	} queueEntry;

	//  this is the structure of data found in the intellikeys eeprom
	#define IK_EEPROM_SN_SIZE 29
	typedef struct
	{
		BYTE serialnumber[IK_EEPROM_SN_SIZE];
		BYTE sensorBlack[IK_NUM_SENSORS];
		BYTE sensorWhite[IK_NUM_SENSORS];
	} eeprom;

	void FindDomain ( IKOverlay *pOverlay, int *domainNumber, bool *bPressAnywhere, int *switchNumber );
	void OverlayRecognitionFeedback();
	void OnStdOverlayChange ();

	bool IsKeystroke(BYTE code);
	void SettleOverlay();

	void OnMembranePress ( int x, int y );
	void OnMembraneRelease ( int x, int y );
	void OnCorrectSwitch ( int switchnum );
	void DoCorrect();
	void OnCorrectMembrane(int x, int y);
	void OnCorrectDone();
	void PostCommand ( BYTE *command );
	void SendCommand ( BYTE *command );

	void ProcessInput();
	void PostSetLED(int number, int value);
	void ProcessCommands();
	void Interpret();
	void UniversalToHID ( int universalCode, int *usagePage, int *usageID );
	void DoMouseButton(int whichButton, int direction);
	void DoMouseMove(int x, int y);
	void PostSound ( int freq, int duration, int volume );

	void PurgeQueues();
	void OnToggle ( int newValue );
	void SweepSound(int iStartFreq, int iEndFreq, int iDuration);
	void OnSwitch ( int nSwitch, int state );
	void OnSensorChange ( int sensor, int value );

	Queue<queueEntry> m_inputQueue;
	Queue<queueEntry> m_commandQueue;
	Queue<queueEntry> m_rawQueue;

	int m_membrane[IK_RESOLUTION_X][IK_RESOLUTION_Y];

	unsigned int m_delayUntil;
	unsigned int m_nextCorrect;
	BYTE m_KeyBoardReport[7];
	BYTE m_MouseReport[3];
	int m_toggle;
	int m_switches[IK_NUM_SWITCHES];
	int m_sensors[IK_NUM_SENSORS];

	int m_currentLevel;

	//  overlay recognition
	int m_lastOverlay;
	unsigned int m_lastOverlayTime;
	int m_currentOverlay;

	//  reading the eeprom
	void StoreEEProm ( BYTE data, BYTE addlsb, BYTE addmsb );
	eeprom m_eepromData;
	unsigned int m_eepromRequestTime[sizeof(eeprom)];
	bool m_eepromDataValid[sizeof(eeprom)];
	bool m_bEepromValid;

	//  for correction
	BYTE m_membranePressedInCorrectMode[IK_RESOLUTION_X][IK_RESOLUTION_X];
	BYTE m_switchesPressedInCorrectMode[IK_NUM_SWITCHES];

	BYTE m_last_membrane[IK_RESOLUTION_X][IK_RESOLUTION_Y];
	BYTE m_last_switches[IK_NUM_SWITCHES];
	bool m_bLastInit;

	void KeySoundVol(int msLength,int volume=-1);

	int m_repeatDomain;
	int m_currentDomain;
	unsigned int  m_repeatAfter;
	bool m_bRepeatLatched ;
	bool m_bRepeatLatchReleased ;
	int  m_nrepeat ;
	unsigned int  m_timeToRespond;
	unsigned int  m_deadUntil ;
	int  m_ndown ;
	bool m_bDidSetup;

	int ExecuteUniversalData(BYTE *thedata, bool bForceKeyUp=false );

	//  track some times for liftoff.
	unsigned int m_lastPress;
	unsigned int m_lastRelease;
	unsigned int m_lastExecute;
	unsigned int m_startDomain;

	int m_counter ;
	int m_lastcode ;

	class IKModifier
	{

	public:
		IKModifier(){m_state = kModifierStateOff;}
		virtual ~IKModifier(){}
		void Execute(int code=0);
		int GetState(){return m_state;}
		void SetState(int state);
		void SetCode (BYTE code ){m_universalCode = code;}
		int m_state;
		int m_universalCode;
		int m_universalCodeOverride;
		void SetDevice(IKDevice *pDev){m_device = pDev;}
		IKDevice *m_device;
	};

	IKModifier m_modShift;
	IKModifier m_modAlt;
	IKModifier m_modControl;
	IKModifier m_modCommand;

	bool m_lights[9];

	bool m_bOpen;

	WriteDataProc m_writeProc;

	int m_index;

	int m_lastCodeUp;

	bool m_bShifted;

	BYTE * m_lastExecuted;

	int m_last5Overlays[5];

	int m_newLevel;

	int m_devType;

	int m_lastSwitch;

	// June 2012 - JR - added for holding Firmware Version info
	unsigned char m_firmwareVersionMajor;
	unsigned char m_firmwareVersionMinor;
};

#endif // !defined(AFX_IKDEVICE_H__4B588751_F075_44F4_BE1D_5B3E7EA7D079__INCLUDED_)


text:
cask 'font-ubuntu-nerd-font-mono' do
  version '2.0.0'
  sha256 '1c63e03728d89bbc6df6d357d156b5adb1c90bde247933c7cb429e6482ad22bb'

  url "https://github.com/ryanoasis/nerd-fonts/releases/download/v#{version}/Ubuntu.zip"
  appcast 'https://github.com/ryanoasis/nerd-fonts/releases.atom'
  name 'Ubuntu Nerd Font Mono (Ubuntu)'
  homepage 'https://github.com/ryanoasis/nerd-fonts'

  font 'Ubuntu Bold Nerd Font Complete Mono.ttf'
  font 'Ubuntu Italic Nerd Font Complete Mono.ttf'
  font 'Ubuntu Bold Italic Nerd Font Complete Mono.ttf'
  font 'Ubuntu Medium Nerd Font Complete Mono.ttf'
  font 'Ubuntu Nerd Font Complete Mono.ttf'
  font 'Ubuntu Medium Italic Nerd Font Complete Mono.ttf'
  font 'Ubuntu Condensed Nerd Font Complete Mono.ttf'
  font 'Ubuntu Light Nerd Font Complete Mono.ttf'
  font 'Ubuntu Light Italic Nerd Font Complete Mono.ttf'
end


text:
import { inject, Lazy } from 'aurelia-framework';
import { HttpClient } from 'aurelia-fetch-client';
import {Router} from 'aurelia-router';
import Moment from 'moment';

// polyfill fetch client conditionally
const fetch = !self.fetch ? System.import('isomorphic-fetch') : Promise.resolve(self.fetch);

@inject(Lazy.of(HttpClient), Router)
export class List {

    emails = [];
    params = {};
    to;
    from;
    before;
    after;
    page;
    pageSize;

    constructor(getHttpClient, router) {
        this.getHttpClient = getHttpClient;
        this.router = router;
        this.that = this;
    }

    async activate(params) {

        await fetch;
        this.http = this.getHttpClient();

        this.http.configure(config => {
            config
                .useStandardConfiguration()
                .withBaseUrl('/api/');
        });

        this.populateFromParams(params);

        // await this.refresh();
    }

    populateFromParams(params) {
        this.params = params;
        this.to = params.to;
        this.from = params.from;
        this.before = params.before;
        this.after = params.after;
        this.page = params.page || 1;
        this.pageSize = params.pageSize || 25;
    }

    async refresh() {

        var query = {
            to: this.to,
            from: this.from,
            before: this.before,
            after: this.after,
            page: this.page,
            pageSize: this.pageSize
        }
        this.router.navigateToRoute('emails', query, { replace: true });

        let result = await this.fetchEmails(
            this.page,
            this.pageSize,
            this.before,
            this.after,
            this.from,
            this.to);
        this.emails = result.emails;
        this.page = result.page;
        this.pageSize = result.pageSize;
        this.count = result.count;
    }

    async fetchEmails(page, pageSize, before, after, from, to) {

        let query = $.param({
            page: page,
            pageSize: pageSize,
            before: before,
            after: after,
            from: from,
            to: to
        });

        // let response = await this.http.fetch(`emails?${query}`);
        // let result = await response.json();
        let result = this.createFixtures(page, pageSize);
        return result;
    }

    createFixtures(page, pageSize) {
        console.log(`Openning: ${page}`);
        let array = [];
        for (var index = 0; index < pageSize; index++) {
            array.push({
                to: `<message-${index}-page-${page}@silvenga.com>`,
                from: "<from@silvenga.com>",
                firstSeen: Moment.now(),
                messageId: `${index}`
            });
        }

        const count = 100;

        return {
            emails: array,
            page: page,
            pageSize: pageSize,
            count: count
        };
    }

    async getPage(page, pageSize) {
        this.page = page;
        this.pageSize = pageSize;
        await this.refresh();
    }
}


text:
using System;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Graphics.Textures;
using osu.Framework.Utils;
using osu.Game.Rulesets.Judgements;
using osu.Game.Screens.Play.HUD;
using osu.Game.Utils;
using osuTK;
using osuTK.Graphics;

namespace osu.Game.Skinning
{
    public class LegacyHealthDisplay : HealthDisplay, ISkinnableDrawable
    {
        private const double epic_cutoff = 0.5;

        private LegacyHealthPiece fill;
        private LegacyHealthPiece marker;

        private float maxFillWidth;

        private bool isNewStyle;

        public bool UsesFixedAnchor { get; set; }

        [BackgroundDependencyLoader]
        private void load(ISkinSource source)
        {
            AutoSizeAxes = Axes.Both;

            var skin = source.FindProvider(s => getTexture(s, "bg") != null);

            // the marker lookup to decide which display style must be performed on the source of the bg, which is the most common element.
            isNewStyle = getTexture(skin, "marker") != null;

            // background implementation is the same for both versions.
            AddInternal(new Sprite { Texture = getTexture(skin, "bg") });

            if (isNewStyle)
            {
                AddRangeInternal(new[]
                {
                    fill = new LegacyNewStyleFill(skin),
                    marker = new LegacyNewStyleMarker(skin),
                });
            }
            else
            {
                AddRangeInternal(new[]
                {
                    fill = new LegacyOldStyleFill(skin),
                    marker = new LegacyOldStyleMarker(skin),
                });
            }

            fill.Current.BindTo(Current);
            marker.Current.BindTo(Current);

            maxFillWidth = fill.Width;
        }

        protected override void Update()
        {
            base.Update();

            fill.Width = Interpolation.ValueAt(
                Math.Clamp(Clock.ElapsedFrameTime, 0, 200),
                fill.Width, (float)Current.Value * maxFillWidth, 0, 200, Easing.OutQuint);

            marker.Position = fill.Position + new Vector2(fill.DrawWidth, isNewStyle ? fill.DrawHeight / 2 : 0);
        }

        protected override void Flash(JudgementResult result) => marker.Flash(result);

        private static Texture getTexture(ISkin skin, string name) => skin?.GetTexture($"scorebar-{name}");

        private static Color4 getFillColour(double hp)
        {
            if (hp < 0.2)
                return LegacyUtils.InterpolateNonLinear(0.2 - hp, Color4.Black, Color4.Red, 0, 0.2);

            if (hp < epic_cutoff)
                return LegacyUtils.InterpolateNonLinear(0.5 - hp, Color4.White, Color4.Black, 0, 0.5);

            return Color4.White;
        }

        public class LegacyOldStyleMarker : LegacyMarker
        {
            private readonly Texture normalTexture;
            private readonly Texture dangerTexture;
            private readonly Texture superDangerTexture;

            public LegacyOldStyleMarker(ISkin skin)
            {
                normalTexture = getTexture(skin, "ki");
                dangerTexture = getTexture(skin, "kidanger");
                superDangerTexture = getTexture(skin, "kidanger2");
            }

            public override Sprite CreateSprite() => new Sprite
            {
                Texture = normalTexture,
                Origin = Anchor.Centre,
            };

            protected override void LoadComplete()
            {
                base.LoadComplete();

                Current.BindValueChanged(hp =>
                {
                    if (hp.NewValue < 0.2f)
                        Main.Texture = superDangerTexture;
                    else if (hp.NewValue < epic_cutoff)
                        Main.Texture = dangerTexture;
                    else
                        Main.Texture = normalTexture;
                });
            }
        }

        public class LegacyNewStyleMarker : LegacyMarker
        {
            private readonly ISkin skin;

            public LegacyNewStyleMarker(ISkin skin)
            {
                this.skin = skin;
            }

            public override Sprite CreateSprite() => new Sprite
            {
                Texture = getTexture(skin, "marker"),
                Origin = Anchor.Centre,
            };

            protected override void Update()
            {
                base.Update();

                Main.Colour = getFillColour(Current.Value);
                Main.Blending = Current.Value < epic_cutoff ? BlendingParameters.Inherit : BlendingParameters.Additive;
            }
        }

        internal abstract class LegacyFill : LegacyHealthPiece
        {
            protected LegacyFill(ISkin skin)
            {
                // required for sizing correctly..
                var firstFrame = getTexture(skin, "colour-0");

                if (firstFrame == null)
                {
                    InternalChild = new Sprite { Texture = getTexture(skin, "colour") };
                    Size = InternalChild.Size;
                }
                else
                {
                    InternalChild = skin.GetAnimation("scorebar-colour", true, true, startAtCurrentTime: false, applyConfigFrameRate: true) ?? Empty();
                    Size = new Vector2(firstFrame.DisplayWidth, firstFrame.DisplayHeight);
                }

                Masking = true;
            }
        }

        internal class LegacyOldStyleFill : LegacyFill
        {
            public LegacyOldStyleFill(ISkin skin)
                : base(skin)
            {
                Position = new Vector2(3, 10) * 1.6f;
            }
        }

        internal class LegacyNewStyleFill : LegacyFill
        {
            public LegacyNewStyleFill(ISkin skin)
                : base(skin)
            {
                Position = new Vector2(7.5f, 7.8f) * 1.6f;
            }

            protected override void Update()
            {
                base.Update();
                Colour = getFillColour(Current.Value);
            }
        }

        public abstract class LegacyMarker : LegacyHealthPiece
        {
            protected Sprite Main;

            private Sprite explode;

            protected LegacyMarker()
            {
                Origin = Anchor.Centre;
            }

            [BackgroundDependencyLoader]
            private void load()
            {
                InternalChildren = new Drawable[]
                {
                    Main = CreateSprite(),
                    explode = CreateSprite().With(s =>
                    {
                        s.Alpha = 0;
                        s.Blending = BlendingParameters.Additive;
                    }),
                };
            }

            public abstract Sprite CreateSprite();

            protected override void LoadComplete()
            {
                base.LoadComplete();

                Current.BindValueChanged(val =>
                {
                    if (val.NewValue > val.OldValue)
                        bulgeMain();
                });
            }

            public override void Flash(JudgementResult result)
            {
                bulgeMain();

                bool isEpic = Current.Value >= epic_cutoff;

                explode.Blending = isEpic ? BlendingParameters.Additive : BlendingParameters.Inherit;
                explode.ScaleTo(1).Then().ScaleTo(isEpic ? 2 : 1.6f, 120);
                explode.FadeOutFromOne(120);
            }

            private void bulgeMain() =>
                Main.ScaleTo(1.4f).Then().ScaleTo(1, 200, Easing.Out);
        }

        public class LegacyHealthPiece : CompositeDrawable
        {
            public Bindable<double> Current { get; } = new Bindable<double>();

            public virtual void Flash(JudgementResult result)
            {
            }
        }
    }
}


text:
require 'colorize'
require 'singleton'

module SimpleBackup
  module Utils
    class Logger
      include Singleton

      TIME_FORMAT = '%Y-%m-%dT%H:%M:%S'

      def initialize
        @buffer = []
        @scope = 0
        @level = :info
        @levels = {
          debug: {weight: 3, color: :light_cyan},
          info: {weight: 2, color: :green},
          warning: {weight: 1, color: :light_yellow},
          error: {weight: 0, color: :red}
        }

       banner = "LOG STARTED #{Time.new.strftime('%Y-%m-%dT%H:%M:%S')}"
        banner2 = "SimpleBackup v#{SimpleBackup::Version::get}"

        banner_length = 0
        banner_length = banner.length if  banner.length > banner_length
        banner_length = banner2.length if banner2.length > banner_length
        banner_length = 80 if 80 > banner_length

        border = '=' * ((banner_length - banner.length) / 2).ceil.to_i
        @buffer << "#{border}==[ #{banner} ]==#{border}"
        border = '=' * ((banner_length - banner2.length) / 2).ceil.to_i
        @buffer << "#{border}==[ #{banner2} ]==#{border}"

        puts @buffer[0].green
        puts @buffer[1].green
      end

      def level=(level)
        check_level(level)
        @level = level
      end

      def scope_start(level = nil, message = nil)
        log level, message unless level.nil? and message.nil?
        @scope += 1
      end

      def scope_end(level = nil, message = nil)
        log level, message unless level.nil? and message.nil?
        @scope -= 1 unless @scope == 0
      end

      def debug(message)
        log(:debug, message)
      end

      def info(message)
        log(:info, message)
      end

      def warning(message)
        log(:warning, message)
      end

      def error(message)
        log(:error, message)
      end

      def log(level, message)
        check_level(level)

        color = @levels[level][:color]
        should_write = @levels[level][:weight] <= @levels[@level][:weight]

        scope_prefix = '..' * @scope
        message = "%s %7s: %s%s" % [Time.new.strftime(TIME_FORMAT), level.to_s.upcase, scope_prefix, message]

        @buffer << message if should_write
        puts message.colorize(color: color) if should_write
      end

      def check_level(level)
        raise "Unknown logging level #{level}" unless @levels.has_key?(level)
      end

      def buffer
        @buffer
      end
    end
  end
end


text:
package it.pacs.rest.cache;

import it.pacs.rest.interfaces.CacheInterface;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author Stefano Pacifici
 */
public class SimpleMemoryCache implements CacheInterface {

    // The default cache size (512kb)
    private static final int DEFAULT_CACHE_SIZE = 512 * 1024;
    // The internal cache
    private final LinkedHashMap<String, CacheEntry> cache;
    // The max cache size
    private final int maxCacheSize;
    // The available cache space
    private int availableCacheSize;

    /**
     * Create a cache with default parameters
     */
    public SimpleMemoryCache() {
        cache = new LinkedHashMap<String, CacheEntry>(1000, 1.1f, true);
        maxCacheSize = DEFAULT_CACHE_SIZE;
        availableCacheSize = DEFAULT_CACHE_SIZE;
    }

    /**
     * Like {@link it.pacs.rest.interfaces.CacheInterface#put(String, String, java.io.InputStream)}, but add an
     * expiration time.
     *
     * @param key         the cache key
     * @param etag        the request etag
     * @param inputStream an {@link java.io.InputStream} which data will be copied in the cache
     * @param expireTime  the time (as milliseconds since Gen. 1st, 1970 GMT) when the data will be considered
     *                    expired
     * @return an InputString backed by data copied in the cache, null if error an occurred
     */
    @Override
    public InputStream put(String key, String etag, InputStream inputStream, long expireTime) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        try {
            int read;
            while ((read = inputStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, read);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

        byte[] data = outputStream.toByteArray();
        int size = data.length;

        // Don't cache data bigger than the half of the cache
        if (size > maxCacheSize / 2)
            return new ByteArrayInputStream(data);

        CacheEntry cacheEntry = new CacheEntry();
        cacheEntry.expireTime = expireTime;
        cacheEntry.data = data;
        cacheEntry.updateTime = System.currentTimeMillis();
        cacheEntry.etag = etag;

        synchronized (cache) {
            availableCacheSize -= size;
            cache.put(key, cacheEntry);
            // Free cache
            if (availableCacheSize <= maxCacheSize / 10) {
                Iterator<Map.Entry<String, CacheEntry>> iterator = cache.entrySet().iterator();
                while (iterator.hasNext() && availableCacheSize <= 0) {
                    Map.Entry<String, CacheEntry> next = iterator.next();
                    availableCacheSize += next.getValue().data.length;
                    iterator.remove();
                }
            }
        }

        return new ByteArrayInputStream(cacheEntry.data);
    }

    /**
     * @return the cache size in bytes
     */
    @Override
    public int cacheSize() {
        return maxCacheSize;
    }

    /**
     * @return the available cache in bytes
     */
    @Override
    public int availableCacheSize() {
        return availableCacheSize;
    }

    /**
     * @param key the cache key
     * @return the timestamp of the last {@link #put(String, String, java.io.InputStream)} for the url, or -1 if the
     *         the url is not cached
     */
    @Override
    public long getUpdateTime(String key) {
        CacheEntry cacheEntry;
        synchronized (cache) {
            cacheEntry = cache.get(key);
        }

        return cacheEntry != null ? cacheEntry.updateTime : -1l;
    }

    /**
     * Return the etag associated with the a previous request
     *
     * @param key the cache key
     * @return the etag
     */
    @Override
    public String getETag(String key) {
        CacheEntry cacheEntry;
        synchronized (cache) {
            cacheEntry = cache.get(key);
        }

        return cacheEntry != null ? cacheEntry.etag : null;
    }

    @Override
    public InputStream get(String key) {
        CacheEntry cacheEntry;
        long now = System.currentTimeMillis();
        synchronized (cache) {
            cacheEntry = cache.get(key);
            if (cacheEntry != null && cacheEntry.expireTime >= 0 && cacheEntry.expireTime < now) {
                availableCacheSize += cacheEntry.data.length;
                cache.remove(key);
                cacheEntry = null;
            }
        }
        return cacheEntry != null ? new ByteArrayInputStream(cacheEntry.data) : null;
    }

    @Override
    public InputStream put(String key, String etag, InputStream inputStream) {
        return put(key, etag, inputStream, -1);
    }

    private class CacheEntry {
        public long expireTime;
        public byte[] data;
        public long updateTime;
        public String etag;
    }
}


text:
There are 2 ways to trigger a test suite: Through the Cli, or through `munit.render`.

### munit.render

Render is the JS trigger for running the munit test suite. Path is only required if no
tests have been added yet.

```
munit.render( [ path, ] options );
```

```js
munit.render( __dirname + '/test/' );
```

### munit cli

If installed globally (`npm install -g munit`) the munit script may be used to manually run
test suites.

```
$ munit /path/to/test
```

# munit Cli Options

### render

The path to render for the test suite. Can be either a file or a directory.

```
$ munit /path/to/test/dir
$ munit -r /path/to/test/dir
$ munit --render=/path/to/test/dir
```

```js
munit.render({
	render: __dirname + '/test/'
});
```

### focus

Namespace(s) to focus tests on. When defined, only tests that fall on those namespaces will be triggered. Can be an array of names, or a single name.

```
$ munit -f core.util
$ munit --focus=core.util
$ munit --focus=core.util,core.network
```

```js
munit.render({
	focus: 'core.util'
});
```

### results

Path to write out the test results.

```
$ munit -o /path/to/results
$ munit --results=/path/to/results
```

```js
munit.render({
	results: __dirname + '/test-results/'
});
```


text:
function clamp_top_n(top_n) {
    // round up
    top_n = Math.floor((top_n + 99) / 100) * 100
    if (top_n < 100) {
        top_n = 100
    }
    if (top_n > 8000) {
        top_n = 8000
    }
    return top_n
}

/**
 * Generate an exercise based on gutenberg-data.js (make sure to import that)
 *
 * @param {number} word_count The exercise will contain this many words
 * @param {number} top_n Sentences will contain only the top N number of words (clamped between 100 and 8000)
 * @param {function} rng A seed for the RNG
 */
function generateExercise(word_count, top_n, rng) {
    top_n = clamp_top_n(top_n)
    let words = [], sentence
    let chars_left = word_count * 5 + 1
    let top_n_bucket = window.sentences_by_top_100[top_n / 100 - 1]
    while (chars_left > 0) {
        sentence = top_n_bucket[Math.floor(rng() * top_n_bucket.length)]
        chars_left -= 1 + sentence.length
        words.splice(words.length, 0, ...sentence.split(' '))
    }

    return new TypeJig.Exercise(words, 0, false, 'ordered');
}

let jig
window.addEventListener('load', () => jig = loadExercisePage(args => {
	const topN = clamp_top_n(args.top==null ? 100 : parseInt(args.top))
	const nWords = args.word_count==null ? 100 : parseInt(args.word_count)

	return {
		generate: (rnd, opt) => generateExercise(nWords, topN, rnd),
		options: { name: "Project Gutenberg sentences for words "+(topN-99)+" to "+topN+"." }
	}
}))


text:
<?xml version="1.0" encoding="UTF-8" ?>
<container xmlns="http://symfony.com/schema/dic/services"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

    <services>
        <service id="nsm_form.form.extension.layout"
                 class="Nsm\Bundle\FormBundle\Form\Extension\Layout\LayoutExtension">
            <tag name="form.type_extension" alias="form"/>
        </service>
    </services>
</container>


text:
#include "universal_include.h"

#include "App/app.h"
#include "Sound/soundsystem.h"

SoundSystem::SoundSystem()
{
}

SoundSystem::~SoundSystem()
{
}

SoundSystem *g_soundSystem;


text:
using System.Reflection;
using iSukces.Code.Interfaces;
using JetBrains.Annotations;

namespace Sample.AppWithCSharpCodeEmbedding.AutoCode
{
    internal class JetbrainsAttributeNullValueChecker : AbstractMemberNullValueChecker
    {
        protected override bool HasMemberNotNullAttribute(MemberInfo mi)
        {
            return mi.GetCustomAttribute<NotNullAttribute>() != null;
        }
    }
}


text:
<?php

/**
 * Muestra todos los errores generados por PHP excepto los Notice.
 */
error_reporting(E_ALL ^ E_NOTICE);

/**
 * Establece la zona horaria predeterminada usada por

 * todas las funciones de fecha/hora en un script
 */
date_default_timezone_set('America/Bogota');

/**
 * Ruta del de inicio del sitio.
 *
 * @global string SITE
 */
define('SITE', '/calculadorafinanciera');
//define('SITE', '');

/**
 * Separador
 *
 * @global string DS
 */
define('DS', DIRECTORY_SEPARATOR);

/**
 * Ruta absoluta del sitio desde el servidor.
 *
 * @global string APP_ROOT
 */
define('APP_ROOT', realpath(dirname(__FILE__)) . DS);

/**
 * Ruta absoluta al directorio principal del sitio.
 *
 * @global string APP_PATH
 */
define('CORE_PATH', APP_ROOT . 'core' . DS);
/**
 * Puerto de la aplicación
 *
 * @global int PORT
 */
define('PORT', 80);

/**
 * Ruta del dominio del sitio.
 *
 * @global string BASE_URL
 */
define('BASE_URL', 'http://' . $_SERVER['SERVER_NAME'] . ":" . PORT . SITE);

/**
 *
 *
 * @global boolean OFF_LINE
 */
define('OFF_LINE', false);

try {
    require_once CORE_PATH . 'config.php';
    require_once CORE_PATH . 'dictionary.php';
    require_once CORE_PATH . 'db.php';
    require_once CORE_PATH . 'autoload.php';
    Dictionary::getClass();
    Dictionary::getInterfaces();
    require_once CORE_PATH . 'exceptionDatabase.php';
    require_once CORE_PATH . 'model.php';
    require_once CORE_PATH . 'request.php';
    require_once CORE_PATH . 'bootstrap.php';
    require_once CORE_PATH . 'controller.php';
    require_once CORE_PATH . 'session.php';
    require_once CORE_PATH . 'view.php';
    Bootstrap::run(new Request);
} catch (Exception $e) {
    $trace = $e->getTrace();
    $i = 0;
    foreach ($trace as $tr) {
        if ($_GET['view_file'])
            $file = "    -file: $tr[file] line: $tr[line]";

        $str .= " $i -- Class:$tr[class]::$tr[function]  $file
";
        $i++;
    }
    die("
" .
            "
 Mensaje   = " . $e->getMessage() .
            "
 Codigo    = " . $e->getCode() .
            "
 Trace     =
" . $str);
}


text:
<!DOCTYPE html>

    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <meta charset="utf-8">
    <title>I244 kaugõpe: 5. praktikum: töö saatmine</title>
    <link href="http://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <link rel="stylesheet" href="../assets/styles/materialize.min.css">
    <link rel="stylesheet" href="../assets/styles/main.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

Turvatest

		Siin saad saata oma töö turvatestimiseks teistele õpilastele.

        	Oma kirjutatud ja töötava lahenduse siia saatmise eest saab 2 lisapunkti.

        	Võib saata nii praktikumides tehtud lehti, kodust projekti kui muud aine raames tehtut. Oluline, et rakendus oleks funktsionaalselt toimiv!

Saada oma töö

            <form method="POST">

Sinu nimi:

		<input type="text" name="nimi" required />

Viide töö versioonihaldusele:

		<input type="url" name="git" required />

Link töötavale rakendusele:

		<input type="url" name="link" required />
		<input type="submit" value="saada!" class="waves-effect waves-light btn" />
            </form>

Saadetud tööd

Nimi	Versioonihaldus	Töötav demo

                <?php include('salvesta.php'); ?>
                <?php include('esitatud.html'); ?>


text:
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#include "utils.h"
#include <iostream>
#include <fstream>
#define MID_PREFIX "v2:"

namespace UTILS_NS
{
namespace PlatformUtils
{
	/**
	 * Create a machine ID for this machine and write it to the .PRODUCT_NAME file
	 * in the user runtime home directory. The machine id is specific to a particular
	 * user on a particular OS install and does not uniquely identify a machine.
	 */
	static std::string CreateMachineId(std::string& midFileName);
	static std::string GetOldMachineId(std::string& midFileName);
	static std::string ReadMIDFromFile(std::string& path);

	std::string GetFirstMACAddress()
	{
		NodeId id;
		try
		{
			PlatformUtils::GetNodeId(id);
		} catch(std::string e)
		{
			return e;
		}
		catch(...)
		{
			return "NoMACAddressFound";
		}
		char result[18];
		std::sprintf(result, "%02x:%02x:%02x:%02x:%02x:%02x",
			id[0],
			id[1],
			id[2],
			id[3],
			id[4],
			id[5]);
		return std::string(result);
	}

	std::string GetMachineId()
	{

		std::string midFileName(std::string(".") + PRODUCT_NAME);
		std::transform(midFileName.begin(), midFileName.end(), midFileName.begin(), tolower);

		std::string midFilePath(FileUtils::GetUserRuntimeHomeDirectory());
		midFilePath = FileUtils::Join(midFilePath.c_str(), midFileName.c_str(), NULL);
		std::string mid(ReadMIDFromFile(midFilePath));

		// If we couldn't read the MID or this is an old MID,
		// create a new one and return it.
		if (mid.empty() || mid.find(MID_PREFIX) != 0)
		{
			mid = CreateMachineId(midFileName);
		}

		return mid;
	}

	static std::string CreateMachineId(std::string& midFileName)
	{
		std::string newMID(MID_PREFIX);
		newMID.append(DataUtils::GenerateUUID());
		newMID.append("|");
		newMID.append(GetOldMachineId(midFileName));

		std::string midFilePath(FileUtils::GetUserRuntimeHomeDirectory());
		midFilePath = FileUtils::Join(midFilePath.c_str(), midFileName.c_str(), NULL);
		std::ofstream myfile;
		myfile.open(midFilePath.c_str());
		myfile << newMID << std::endl;
		myfile.close();

		return newMID;
	}

	static std::string GetOldMachineId(std::string& midFileName)
	{
		// Search for an old MID stored in a file
		std::vector<std::string> possibleMIDFiles;
		std::string path;
 		if (EnvironmentUtils::Has("KR_RUNTIME"))
		{
			path = EnvironmentUtils::Get("KR_RUNTIME");
			path = FileUtils::Join(path.c_str(), "..", "..", "..", midFileName.c_str(), NULL);
			possibleMIDFiles.push_back(path);
		}

		path = FileUtils::GetUserRuntimeHomeDirectory();
		path = FileUtils::Join(path.c_str(), midFileName.c_str(), NULL);
		possibleMIDFiles.push_back(path);

		path = FileUtils::GetSystemRuntimeHomeDirectory();
		path = FileUtils::Join(path.c_str(), midFileName.c_str(), NULL);
		possibleMIDFiles.push_back(path);

		std::string mid;
		for (size_t i = 0; i < possibleMIDFiles.size(); i++)
		{
			std::string& currentPath = possibleMIDFiles[i];
			mid = ReadMIDFromFile(currentPath);
			if (!mid.empty())
				return mid;
		}

		// Alternatively hash the MAC address and use that as the old MID
		std::string MACAddress(PlatformUtils::GetFirstMACAddress());
		return DataUtils::HexMD5(MACAddress);
	}

	static std::string ReadMIDFromFile(std::string& path)
	{
		if (FileUtils::IsFile(path))
		{
			std::ifstream file(path.c_str());
			if (!file.bad() && !file.fail() && ! file.eof())
			{
				std::string line;
				std::getline(file, line);
				line = FileUtils::Trim(line);
				file.close();
				return line;
			}
		}
		return std::string();
	}
}
}