text:
package core

import (
	"encoding/json"
	"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/oci/oci-go-sdk/v43/common"
)

// AmdMilanBmPlatformConfig The platform configuration of a bare metal instance that uses an E4 shape
// (the AMD Milan platform).
type AmdMilanBmPlatformConfig struct {

	// The number of NUMA nodes per socket (NPS).
	NumaNodesPerSocket AmdMilanBmPlatformConfigNumaNodesPerSocketEnum `mandatory:"false" json:"numaNodesPerSocket,omitempty"`
}

func (m AmdMilanBmPlatformConfig) String() string {
	return common.PointerString(m)
}

// MarshalJSON marshals to json representation
func (m AmdMilanBmPlatformConfig) MarshalJSON() (buff []byte, e error) {
	type MarshalTypeAmdMilanBmPlatformConfig AmdMilanBmPlatformConfig
	s := struct {
		DiscriminatorParam string `json:"type"`
		MarshalTypeAmdMilanBmPlatformConfig
	}{
		"AMD_MILAN_BM",
		(MarshalTypeAmdMilanBmPlatformConfig)(m),
	}

	return json.Marshal(&s)
}

// AmdMilanBmPlatformConfigNumaNodesPerSocketEnum Enum with underlying type: string
type AmdMilanBmPlatformConfigNumaNodesPerSocketEnum string

// Set of constants representing the allowable values for AmdMilanBmPlatformConfigNumaNodesPerSocketEnum
const (
	AmdMilanBmPlatformConfigNumaNodesPerSocketNps0 AmdMilanBmPlatformConfigNumaNodesPerSocketEnum = "NPS0"
	AmdMilanBmPlatformConfigNumaNodesPerSocketNps1 AmdMilanBmPlatformConfigNumaNodesPerSocketEnum = "NPS1"
	AmdMilanBmPlatformConfigNumaNodesPerSocketNps2 AmdMilanBmPlatformConfigNumaNodesPerSocketEnum = "NPS2"
	AmdMilanBmPlatformConfigNumaNodesPerSocketNps4 AmdMilanBmPlatformConfigNumaNodesPerSocketEnum = "NPS4"
)

var mappingAmdMilanBmPlatformConfigNumaNodesPerSocket = map[string]AmdMilanBmPlatformConfigNumaNodesPerSocketEnum{
	"NPS0": AmdMilanBmPlatformConfigNumaNodesPerSocketNps0,
	"NPS1": AmdMilanBmPlatformConfigNumaNodesPerSocketNps1,
	"NPS2": AmdMilanBmPlatformConfigNumaNodesPerSocketNps2,
	"NPS4": AmdMilanBmPlatformConfigNumaNodesPerSocketNps4,
}

// GetAmdMilanBmPlatformConfigNumaNodesPerSocketEnumValues Enumerates the set of values for AmdMilanBmPlatformConfigNumaNodesPerSocketEnum
func GetAmdMilanBmPlatformConfigNumaNodesPerSocketEnumValues() []AmdMilanBmPlatformConfigNumaNodesPerSocketEnum {
	values := make([]AmdMilanBmPlatformConfigNumaNodesPerSocketEnum, 0)
	for _, v := range mappingAmdMilanBmPlatformConfigNumaNodesPerSocket {
		values = append(values, v)
	}
	return values
}


text:
def double(x):
    "A very good implementation of double for x<6"
    if x < 6:
        return x*2
    else:
        return x*3

redpajama_set_name: RedPajamaGithub


text:
module Chapter18 where

import Prelude hiding (lookup)
import System.IO
import Control.Monad (liftM, ap)
import Control.Monad.Identity
import Chapter8 (getInt)
import Data.Time
import System.Locale hiding (defaultTimeLocale)
import System.IO.Unsafe (unsafePerformIO)

-- Programming with monads
-- ^^^^^^^^^^^^^^^^^^^^^^^

-- The basics of input/output
-- ^^^^^^^^^^^^^^^^^^^^^^^^^^

-- Reading input is done by getLine and getChar: see Prelude for details.

--  getLine :: IO String
--  getChar :: IO Char

-- Text strings are written using
--
--  putStr :: String -> IO ()
--  putStrLn :: String -> IO ()

-- A hello, world program

helloWorld :: IO ()
helloWorld = putStr "Hello, World!"

-- Simple examples

readWrite :: IO ()

readWrite =
    do
      getLine
      putStrLn "one line read"

readEcho :: IO ()

readEcho =
    do
      line <-getLine
      putStrLn ("line read: " ++ line)

-- Adding a sequence of integers from the input

sumInts :: Integer -> IO Integer

sumInts s
  = do n <- getInt
       if n==0
          then return s
          else sumInts (s+n)

-- Adding a list of integers, using an accumulator

sumAcc :: Integer -> [Integer] -> Integer

sumAcc s [] = s
sumAcc s (n:ns)
  = if n==0
       then s
       else sumAcc (s+n) ns

-- Addiing a sequence of integers, courteously.

sumInteract :: IO ()
sumInteract
  = do putStrLn "Enter integers one per line"
       putStrLn "These will be summed until zero is entered"
       sum <- sumInts 0
       putStr "The sum is "
       print sum

-- Further I/O
-- ^^^^^^^^^^^

-- Interaction at the terminal

copyInteract :: IO ()

copyInteract =
    do
      hSetBuffering stdin LineBuffering
      copyEOF
      hSetBuffering stdin NoBuffering

copyEOF :: IO ()

copyEOF =
    do
      eof <- isEOF
      if eof
        then return ()
        else do line <- getLine
                putStrLn line
                copyEOF

-- Input and output as lazy lists

-- Reverse all the lines in the input.

listIOprog :: String -> String

listIOprog = unlines . map reverse . lines

-- Generating random numbers

randomInt :: Integer -> IO Integer
randomInt n =
    do
      time <- getCurrentTime
      return ( (`rem` n) $ read $ take 6 $ formatTime defaultTimeLocale "%q" time)

randInt :: Integer -> Integer
randInt = unsafePerformIO . randomInt

-- The calculator
-- ^^^^^^^^^^^^^^

-- This is available separately in the Calculator directory.

-- The do notation revisited
-- ^^^^^^^^^^^^^^^^^^^^^^^^^

addOneInt :: IO ()

addOneInt
  = do line <- getLine
       putStrLn (show (1 + read line :: Int))

addOneInt'
  = getLine >>= \line ->
    putStrLn (show (1 + read line :: Int))

-- Monads for Functional Programming
-- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

-- The definition of the Monad class
--  class Monad m where
--    (>>=)  :: m a -> (a -> m b) -> m b
--    return :: a -> m a
--    fail   :: String -> m a

-- Kelisli composition for monadic functions.

-- (>@>) :: Monad m => (a -> m b) ->
--                     (b -> m c) ->
--                     (a -> m c)

-- f >@> g = \ x -> (f x) >>= g

-- Some examples of monads
-- ^^^^^^^^^^^^^^^^^^^^^^^

-- Some examples from the standard prelude.

-- The list monad

--  instance Monad [] where
--    xs >>= f  = concat (map f xs)
--    return x  = [x]
--    zero      = []

-- The Maybe monad

--  instance Monad Maybe where
--    (Just x) >>= k  =  k x
--    Nothing  >>= k  =  Nothing
--    return          =  Just

-- The parsing monad

--  data SParse a b = SParse (Parse a b)

--  instance Monad (SParse a) where
--    return x = SParse (succeed x)
--    zero     = SParse fail
--    (SParse pr) >>= f
--      = SParse (\s -> concat [ sparse (f x) rest | (x,rest) <- pr st ])

--  sparse :: SParse a b -> Parse a b
--  sparse (SParse pr) = pr

-- A state monad (the state need not be a table; this example is designed
-- to support the example discussed below.)

type Table a = [a]

data State a b = State (Table a -> (Table a , b))

instance Monad (State a) where

  return x = State (\tab -> (tab,x))

  (State st) >>= f
    = State (\tab -> let
                     (newTab,y)    = st tab
                     (State trans) = f y
                     in
                     trans newTab)

instance Applicative (State a) where
  pure = return
  (<*>) = ap

instance Functor (State a) where
  fmap = liftM

-- Example: Monadic computation over trees
-- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

-- A type of binary trees.

data Tree a = Nil | Node a (Tree a) (Tree a)
              deriving (Eq,Ord,Show)

-- Summing a tree of integers

-- A direct solution:

sTree :: Tree Integer -> Integer

sTree Nil            = 0
sTree (Node n t1 t2) = n + sTree t1 + sTree t2

-- A monadic solution: first giving a value of type Identity Int ...

sumTree :: Tree Integer -> Identity Integer

sumTree Nil = return 0

sumTree (Node n t1 t2)
  = do num <- return n
       s1  <- sumTree t1
       s2  <- sumTree t2
       return (num + s1 + s2)

-- ... then adapted to give an Int solution

sTree' :: Tree Integer -> Integer

sTree' = identity . sumTree

identity :: Identity a -> a

identity (Identity x) = x

-- Using a state monad in a tree calculation
-- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

-- The top level function ...

numTree :: Eq a => Tree a -> Tree Integer

-- ... and the function which does all the work:

numberTree :: Eq a => Tree a -> State a (Tree Integer)

-- Its structure mirrors exactly the structure of the earlier program to
-- sum the tree.

numberTree Nil = return Nil

numberTree (Node x t1 t2)
  = do num <- numberNode x
       nt1 <- numberTree t1
       nt2 <- numberTree t2
       return (Node num nt1 nt2)

-- The work of the algorithm is done node by node, hence the function

numberNode :: Eq a => a -> State a Integer

numberNode x = State (nNode x)

--
-- Looking up a value in the table; will side-effect the table if the value
-- is not present.

nNode :: Eq a => a -> (Table a -> (Table a , Integer))
nNode x table
  | elem x table        = (table      , lookup x table)
  | otherwise           = (table++[x] , integerLength table)
    where
      integerLength = toInteger.length

-- Looking up a value in the table when known to be present

lookup :: Eq a => a -> Table a -> Integer

lookup x tab =
    locate 0 tab
           where
             locate n (y:ys) =
                 if x==y then n else locate (n+1) ys

-- Extracting a value froma state monad.

runST :: State a b -> b
runST (State st) = snd (st [])

-- The top-level function defined eventually.

numTree = runST . numberTree

-- Example tree

egTree :: Tree String

egTree = Node "Moon"
               (Node "Ahmet" Nil Nil)
               (Node "Dweezil"
                        (Node "Ahmet" Nil Nil)
                        (Node "Moon" Nil Nil))


text:
import Boom from 'boom';
import JWT from 'jsonwebtoken';
import Moment from 'moment';
import Platform from 'platform';
import _ from 'lodash';

const ModelResolver = requireF('core/services/resolvers/ModelResolver');

const {
  maxSessions,
  secret,
} = conf.get();

export default class AuthJWTLogin {
  DEFAULT_EXPIRY = 604800;

  constructor(request) {
    this.request = request;
    this.modelResolver = new ModelResolver();
  }

  parseCredentials() {
    const {
      username,
      email,
      password,
    } = this.request.payload;

    let credentials = {
      password,
    };

    if (username) {
      // login with username
      credentials = {
        username,
        ...credentials,
      };
    } else if (email) {
      // login with email
      credentials = {
        email,
        ...credentials,
      };
    }

    return credentials;
  }

  login = async (request, reply) => {
    const credentials = this.parseCredentials();
    const {
      user,
      session,
    } = this.modelResolver.getModels(['user', 'session']);

    const {
      password,
    } = credentials;

    const credentialsRequested = _.omit(credentials, 'password');

    // check if current credentials is valid in database
    const instance = await user.findOne({
      where: credentialsRequested,
    });
    if (instance && instance.validPassword(password)) {
      const existingSessions = await session.count({
        include: {
          model: user,
          where: {
            id: instance.id,
          },
        },
      });
      if (existingSessions >= maxSessions) {
        return Boom.unauthorized(this.request.t('error.user.login.tooManySessions'));
      }

      const token = await this.postLogin(request, instance, credentialsRequested);

      return reply({
        token,
      });
    }

    // if not valid, return the user.login.failed translated message
    return reply(Boom.unauthorized(this.t('error.user.login.failed')));
  }

  postLogin = async (request, user, credentialsRequested) => {
    const sessionModel = this.modelResolver.getModel('session');
    const expiry = Moment().add(this.DEFAULT_EXPIRY, 's').unix();
    const oldSession = await sessionModel.findOne({
      where: {
        userId: user.id,
      },
    });
    if (oldSession) {
      await oldSession.update({
        expiry,
      });
      return oldSession.token;
    }

    const token = JWT.sign({
      id: user.id,
      ...credentialsRequested,
    }, secret);
    const platform = Platform.parse(request.headers['user-agent']);
    await sessionModel.create({
      userId: user.id,
      token,
      platform: platform.description,
      expiry,
    });
    return token;
  }
}


text:
package com.amazonaws.services.simplesystemsmanagement.model.transform;

import java.util.List;
import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.simplesystemsmanagement.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * MaintenanceWindowFilterMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class MaintenanceWindowFilterMarshaller {

    private static final MarshallingInfo<String> KEY_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("Key").build();
    private static final MarshallingInfo<List> VALUES_BINDING = MarshallingInfo.builder(MarshallingType.LIST).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("Values").build();

    private static final MaintenanceWindowFilterMarshaller instance = new MaintenanceWindowFilterMarshaller();

    public static MaintenanceWindowFilterMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(MaintenanceWindowFilter maintenanceWindowFilter, ProtocolMarshaller protocolMarshaller) {

        if (maintenanceWindowFilter == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(maintenanceWindowFilter.getKey(), KEY_BINDING);
            protocolMarshaller.marshall(maintenanceWindowFilter.getValues(), VALUES_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
local _M = {}

--------------------------------------------------------------------------------
-- Constants
--------------------------------------------------------------------------------

_M.DELAY = {
	NONE = 0,
	MASH = 1,
	NORMAL = 2,
}

--------------------------------------------------------------------------------
-- Variables
--------------------------------------------------------------------------------

local _next

--------------------------------------------------------------------------------
-- Public Functions
--------------------------------------------------------------------------------

function _M.cycle()
	if _next then
		if _next.frames == 0 then
			joypad.set(_next.buttons)
			_next = nil
		else
			_next.frames = _next.frames - 1
		end
	end
end

function _M.is_clear()
	return not _next
end

function _M.press(buttons, delay_type)
	if _next or (emu.islagged() and delay_type ~= _M.DELAY.NONE) then
		return false
	end

	if not delay_type then
		delay_type = _M.DELAY.NORMAL
	end

	local delay = 0

	if delay_type == _M.DELAY.MASH then
		delay = math.random(1, 3)
	elseif delay_type == _M.DELAY.NORMAL then
		delay = math.random(6, 10)
	end

	local send_buttons = {}

	for k, v in pairs(buttons) do
		send_buttons[v] = true
	end

	_next = {
		frames = delay,
		buttons = send_buttons
	}

	return true
end

return _M


text:
{% extends "base/backend_master.html" %}

{% block title %} Head Add {% endblock %}
{% load staticfiles %}
{% block child_page_css %}
    <link href="{% static 'css/tree.css' %}" rel="stylesheet">

{% endblock %}
{% block childPage %}

HEADS TREE

                                        more_vert

                                            Add New Ledger Head

                                    {{ tree | safe  }}

{% include 'accounting/modals/edit_head.html' %}
{% endblock %}

{% load staticfiles %}
{% block child_page_js %}

{% endblock %}


text:
<?php

class Permissions
{
	private $db;

	/**
	 * @var array
	 */
	protected $reserved_permissions = array(
		'admin_forum',
		'manage_membergroups',
		'manage_permissions',
	);

	/**
	 * @var string[]
	 */
	private $illegal_permissions = array();

	/**
	 * @var array
	 */
	protected $illegal_guest_permissions = array(
		'delete_replies',
		'karma_edit',
		'poll_add_own',
		'pm_read',
		'pm_send',
		'profile_identity',
		'profile_extra',
		'profile_title',
		'profile_remove',
		'profile_set_avatar',
		'profile_view_own',
		'mark_any_notify',
		'mark_notify',
		'admin_forum',
		'manage_boards',
		'manage_attachments',
		'manage_smileys',
		'edit_news',
		'access_mod_center',
		'moderate_forum',
		'issue_warning',
		'manage_membergroups',
		'manage_permissions',
		'manage_bans',
		'move_own',
		'modify_replies',
		'send_mail',
		'approve_posts',
		'postby_email',
		'approve_emails',
		'like_posts',
	);

	/**
	 * Load a few illegal permissions into the class and context.
	 *
	 * - Calls hook: integrate_load_illegal_permissions
	 * - Calls hook: integrate_load_illegal_guest_permissions
	 */
	public function __construct()
	{
		$this->db = database();
		$this->loadIllegal();
		$this->loadIllegalGuest();
	}

	/**
	 * Return the list of illegal permissions
	 *
	 * @return string[]
	 */
	public function getIllegalPermissions()
	{
		return $this->illegal_permissions;
	}

	/**
	 * Return the list of illegal guest permissions
	 *
	 * @return string[]
	 */
	public function getIllegalGuestPermissions()
	{
		return $this->illegal_guest_permissions;
	}

	/**
	 * Loads those reserved permissions into context.
	 */
	public function loadIllegal()
	{
		global $context;

		foreach ($this->reserved_permissions as $illegal_permission)
		{
			if (!allowedTo($illegal_permission))
			{
				$this->illegal_permissions[] = $illegal_permission;
			}
		}

		$context['illegal_permissions'] = &$this->illegal_permissions;
		call_integration_hook('integrate_load_illegal_permissions', array(&$this->illegal_permissions));
	}

	/**
	 * Loads those permissions guests cannot have, into context.
	 */
	public function loadIllegalGuest()
	{
		global $context;

		$context['non_guest_permissions'] = &$this->illegal_guest_permissions;
		call_integration_hook('integrate_load_illegal_guest_permissions', array(&$this->illegal_guest_permissions));
	}

	/**
	 * Deletes permissions.
	 *
	 * @param string[] $permissions
	 * @param string[] $where
	 * @param mixed[]  $where_parameters = array() or values used in the where statement
	 */
	public function deletePermissions($permissions, $where = array(), $where_parameters = array())
	{
		if (count($this->illegal_permissions) > 0)
		{
			$where[] = 'permission NOT IN ({array_string:illegal_permissions})';
			$where_parameters['illegal_permissions'] = $this->illegal_permissions;
		}
		$where[] = 'permission IN ({array_string:permissions})';
		$where_parameters['permissions'] = $permissions;

		$this->db->query('', '
			DELETE FROM {db_prefix}permissions
			WHERE ' . implode(' AND ', $where),
			$where_parameters
		);
	}

	/**
	 * This function updates the permissions of any groups based on the given groups.
	 *
	 * @param mixed[]|int $parents (array or int) group or groups whose children are to be updated
	 * @param int|null    $profile = null an int or null for the customized profile, if any
	 */
	public function updateChild($parents, $profile = null)
	{
		// All the parent groups to sort out.
		if (!is_array($parents))
		{
			$parents = array($parents);
		}

		// Find all the children of this group.
		$request = $this->db->query('', '
			SELECT id_parent, id_group
			FROM {db_prefix}membergroups
			WHERE id_parent != {int:not_inherited}
				' . (empty($parents) ? '' : 'AND id_parent IN ({array_int:parent_list})'),
			array(
				'parent_list' => $parents,
				'not_inherited' => -2,
			)
		);
		$children = array();
		$parents = array();
		$child_groups = array();
		while ($row = $this->db->fetch_assoc($request))
		{
			$children[$row['id_parent']][] = $row['id_group'];
			$child_groups[] = $row['id_group'];
			$parents[] = $row['id_parent'];
		}
		$this->db->free_result($request);

		$parents = array_unique($parents);

		// Not a sausage, or a child?
		if (empty($children))
		{
			return false;
		}

		// Need functions that modify permissions...
		require_once(SUBSDIR . '/ManagePermissions.subs.php');

		// First off, are we doing general permissions?
		if ($profile < 1 || $profile === null)
		{
			// Fetch all the parent permissions.
			$request = $this->db->query('', '
				SELECT id_group, permission, add_deny
				FROM {db_prefix}permissions
				WHERE id_group IN ({array_int:parent_list})',
				array(
					'parent_list' => $parents,
				)
			);
			$permissions = array();
			while ($row = $this->db->fetch_assoc($request))
			{
				foreach ($children[$row['id_group']] as $child)
				{
					$permissions[] = array(
						'id_group' => (int) $child,
						'permission' => $row['permission'],
						'add_deny' => $row['add_deny'],
					);
				}
			}
			$this->db->free_result($request);

			$this->db->query('', '
				DELETE FROM {db_prefix}permissions
				WHERE id_group IN ({array_int:child_groups})',
				array(
					'child_groups' => $child_groups,
				)
			);

			// Finally insert.
			if (!empty($permissions))
			{
				replacePermission($permissions);
			}
		}

		// Then, what about board profiles?
		if ($profile != -1)
		{
			$profileQuery = $profile === null ? '' : ' AND id_profile = {int:current_profile}';

			// Again, get all the parent permissions.
			$request = $this->db->query('', '
				SELECT id_profile, id_group, permission, add_deny
				FROM {db_prefix}board_permissions
				WHERE id_group IN ({array_int:parent_groups})
					' . $profileQuery,
				array(
					'parent_groups' => $parents,
					'current_profile' => $profile !== null && $profile ? $profile : 1,
				)
			);
			$permissions = array();
			while ($row = $this->db->fetch_assoc($request))
			{
				foreach ($children[$row['id_group']] as $child)
				{
					$permissions[] = array($row['permission'], $child, $row['add_deny'], $row['id_profile']);
				}
			}
			$this->db->free_result($request);

			$this->db->query('', '
				DELETE FROM {db_prefix}board_permissions
				WHERE id_group IN ({array_int:child_groups})
					' . $profileQuery,
				array(
					'child_groups' => $child_groups,
					'current_profile' => $profile !== null && $profile ? $profile : 1,
				)
			);

			// Do the insert.
			if (!empty($permissions))
			{
				replaceBoardPermission($permissions);
			}
		}
	}
}


text:
package agozon

func (a *Request) BrowseNodeLookup() {

}


text:
package util.https;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

public class HttpHelper {

	private static final String CHARSET_UTF8 = HTTP.UTF_8;
	private static HttpClient customerHttpClient;

	private HttpHelper() {

	}

	public static String GetResponse(final Context context, final String url,
			final NameValuePair... nameValuePairs) {
		String strResult;

		strResult = "";

		FutureTask<String> task = new FutureTask<String>(
				new Callable<String>() {
					@Override
					public String call() throws Exception {
						List<NameValuePair> params = new ArrayList<NameValuePair>();
						if (nameValuePairs != null) {
							for (int i = 0; i < nameValuePairs.length; i++) {
								params.add(nameValuePairs[i]);

								System.out.println(nameValuePairs[i]);
							}
						}

						UrlEncodedFormEntity urlEncoded = new UrlEncodedFormEntity(
								params, CHARSET_UTF8);

						System.out.println(url);

						HttpPost httpPost = new HttpPost(url);
						httpPost.setEntity(urlEncoded);

						if (isNetWorkAvailable(context) == true) {
							HttpClient client = getHttpClient(context);// >>>
							HttpResponse response = client.execute(httpPost);// >>>
							int res = response.getStatusLine().getStatusCode();
							if (res != HttpStatus.SC_OK) {
								Log.i("fanjishuo____GetResponse", "res"+res);
								throw new RuntimeException("请求失败");
							}
							HttpEntity resEntity = response.getEntity();

							return (resEntity == null) ? null : EntityUtils
									.toString(resEntity, CHARSET_UTF8);
						} else {
							return "false";
						}
					}
				});
		new Thread(task).start();
		try {
			strResult = task.get();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return strResult;
	}

	private static HttpClient getHttpClient(Context context) {
		if (null == customerHttpClient) {
			HttpParams params = new BasicHttpParams();
			// 设置一些基本参数
			HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
			HttpProtocolParams.setContentCharset(params, CHARSET_UTF8);
			HttpProtocolParams.setUseExpectContinue(params, true);
			HttpProtocolParams
					.setUserAgent(
							params,
							"Mozilla/5.0(Linux;U;Android 2.2.1;en-us;Nexus One Build.FRG83) "
									+ "AppleWebKit/553.1(KHTML,like Gecko) Version/4.0 Mobile Safari/533.1");
			// 超时设置
			/* 从连接池中取连接的超时时间 */
			ConnManagerParams.setTimeout(params, 1000);
			/* 连接超时 */
			int ConnectionTimeOut = 3000;

			HttpConnectionParams
					.setConnectionTimeout(params, ConnectionTimeOut);
			/* 请求超时 */
			HttpConnectionParams.setSoTimeout(params, 4000);
			// 设置我们的HttpClient支持HTTP和HTTPS两种模式
			SchemeRegistry schReg = new SchemeRegistry();
			schReg.register(new Scheme("http", PlainSocketFactory
					.getSocketFactory(), 80));
			schReg.register(new Scheme("https", SSLSocketFactory
					.getSocketFactory(), 443));

			// 使用线程安全的连接管理来创建HttpClient
			ClientConnectionManager conMgr = new ThreadSafeClientConnManager(
					params, schReg);
			customerHttpClient = new DefaultHttpClient(conMgr, params);
		}
		return customerHttpClient;
	}

	public static boolean isNetWorkAvailable(Context context) {
		// ConnectivityManager:主要管理和网络连接相关的操作
		ConnectivityManager cm = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);// 获取系统的连接服务
		// 获取代表联网状态的NetWorkInfo对象
		NetworkInfo info = cm.getActiveNetworkInfo();
		boolean status = info != null && info.isConnected();
		return status;
	}
}


text:
function [labels, nodes, edges] = imToGraph(im, maxSegSize)
if (size(im, 3) > 1)
    im = rgb2gray(im);
end

segmented = segmentation(im, 4, 'pso');
labels = label(segmented);
stats = regionprops(labels, 'Area');
labels(~ismember(labels, find([stats.Area] < maxSegSize))) = 0;
[nodes, edges] = imRAG(labels);
end


text:
<!DOCTYPE html>

<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link href="/releases/4.3.0/css/style.css" rel="stylesheet" />

<title>-buildpath PATH</title>
<meta name="generator" content="Jekyll v3.8.5" />
<meta property="og:title" content="-buildpath PATH" />
<meta property="og:locale" content="en_US" />
<meta name="description" content="The -buildpath instruction is the main mechanism to add build-time dependencies to a project. A dependency is either another project in the workspace, or a bundle in a repository. The -buildpath is only used during compile and build time; it is never used to run projects. Because -buildpath dependencies are only used compile time it's recommended to add bundles containing only APIs; you don't need bundles containing implementations." />
<meta property="og:description" content="The -buildpath instruction is the main mechanism to add build-time dependencies to a project. A dependency is either another project in the workspace, or a bundle in a repository. The -buildpath is only used during compile and build time; it is never used to run projects. Because -buildpath dependencies are only used compile time it's recommended to add bundles containing only APIs; you don't need bundles containing implementations." />

			Intro
			Headers
			Instructions
			Macros
			Commands

<button class="dropbtn">4.3.0</button>

Introduction

How to install bnd

Guided Tour

Guided Tour Workspace & Projects

Concepts

Best practices

Build

Project Setup

Generating JARs

Versioning

Baselining

Service Components

Metatype

Contracts

Bundle Annotations

Accessor Properties

SPI Annotations

Resolving Dependencies

Launching

Startlevels

Testing

Testing with Launchpad

Packaging Applications

JPMS Libraries

Wrapping Libraries to OSGi Bundles

Generating Documentation

Commands

For Developers

Tools bound to bnd

Headers

Instruction Reference

Instruction Index

Macro Reference

Macro Index

Plugins

Settings

Errors

Warnings

Frequently Asked Questions

 -buildpath PATH

The -buildpath instruction is the main mechanism to add build-time dependencies to a project. A dependency is either another project in the workspace, or a bundle in a repository. The -buildpath is only used during compile and build time; it is never used to run projects.  Because -buildpath dependencies are only used compile time it's recommended to add bundles containing only APIs; you don't need bundles containing implementations.

The `-buildpath

Example

An example of the -buildpath could be the following, where three dependencies are defined:

-buildpath: \
	some.other.workspace.project;version=project,\
	osgi.core;version=4.3.1,\
	osgi.cmpn;version=4.3.1

See Also

-testpath

TODO

New function wildcards for bsns & additional repos that can limit the repos (done by Neil)

GitHub


text:
package io.scaledml.features;

import org.junit.Test;

import static org.junit.Assert.*;

public class BinningTest {

    @Test
    public void testGetInsertionPoint() throws Exception {
        Binning binning = new Binning();
        for (int i = 0; i < 100; i++) {
            binning.addPercentile(i * 0.1);
        }
        binning.finishBuild();
        for (int i = 0; i < 100; i++) {
            assertEquals(i, binning.getInsertionPoint(i * 0.1));
            assertEquals(i, binning.getInsertionPoint(i * 0.1 + 0.005));
        }
    }

    @Test
    public void testGetNumberOfValuesBetween1() throws Exception {
        Binning binning = new Binning();
        for (int i = 0; i < 100; i++) {
            binning.addPercentile(i * 0.1);
        }
        binning.finishBuild();
        for (int i = 0; i < 99; i++) {
            assertEquals("i=" + i, 1, binning.getNumberOfValuesBetween(i * 0.1, i * 0.1 + 0.1));
            assertEquals("i=" + i, 1, binning.getNumberOfValuesBetween(i * 0.1 + 0.005, i * 0.1 + 0.105));
        }
        assertEquals(1, binning.getNumberOfValuesBetween(9.9, 10.));
        assertEquals(0, binning.getNumberOfValuesBetween(10., 10.1));
        assertEquals(0, binning.getNumberOfValuesBetween(-0.1, 0.));
    }
}


text:
/* WARNING: THIS IS A FILE GENERATED BY gennorm.js. DO NOT EDIT BY HAND. */
// !data nfc/Mymr nfd/Mymr nfc/Zyyy nfd/Zyyy


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

    <title>Autojar</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <link href="../css/moc.css"  rel="stylesheet" type="text/css" />
    <link href="../css/de.css"  rel="stylesheet" type="text/css" />
    <link href="../css/stdFooter.css"  rel="stylesheet" type="text/css" />

Automatisches Erzeugen von Java-Archiven

Allgemeines	Kommandozeilenversion	Eclipse-Plugin

        Bernd Eggink,  monoped@users.sourceforge.net
        Projektseite:

                    Englische Version

Aufruf

Optionen

Dateiparameter

Spezielle Parameter

Reflection

Beispiele

Reflection

Wenn die Option -d angegeben ist, durchsucht Autojar den Bytecode nach Aufrufen
von Class.forName(name). Für jede Fundstelle wird eine
Meldung ausgegeben. Ist der Klassenname name im Bytecode
als Konstante (Stringliteral) abgelegt, kennt Autojar die zu ladende Klasse;
die Meldung lautet dann z.B.

* Dynamic loading: class Test, method g, name="Blah"

Wurde die Option -a angegeben (impliziert -d), versucht Autojar,
diese Klasse so einzubinden wie eine statisch referenzierte. Falls das gelingt,
sieht die Meldung so aus:

* Dynamic loading: class Test, method g, name="Blah" (RESOLVED)

Ist name kein Literal, sondern eine Referenz, lässt
sich nicht feststellen, um welche Klasse es sich handelt. Solche Aufrufe werden
am Ende des Programmlaufs in einer getrennten Liste protokolliert. Beispiel:

* Dynamic loading, unknown classname:
    class Test, method f
    class Foo, method bar

Das resultierende Archiv ist dann möglicherweise unvollständig und seine
Benutzung kann zu ClassNotFound - Exceptions führen; dies allerdings
nur, wenn die entsprechenden Class.forName() - Aufrufe auch
tatsächlich ausgeführt werden.

Aufrufe von Class.forName() in compilergenerierten Methoden
werden ignoriert.

                  Spezielle Parameter

Beispiele

        Created 2011-05-16 by mopcoge


text:
<link rel="ractive" href="./shared/header.html" name="Header">

		{{#if !stats.lastUpdate}}

Loading...

		{{else}}

						FASTEST CDN

						(last 30 days / Last update: {{formatDate(stats.lastUpdate)}})

							Average response time:
							{{stats.cedexis.bestcdnspeed[0][1]}} MS

							Total HTTP requests:
							{{formatNumber(stats.cdn.percdn[stats.cedexis.bestcdnspeed[0][0]])}}

							Average response time:
							{{stats.cedexis.bestcdnspeed[1][1]}} MS

							Total HTTP requests:
							{{formatNumber(stats.cdn.percdn[stats.cedexis.bestcdnspeed[1][0]])}}

							Average response time:
							{{stats.cedexis.bestcdnspeed[2][1]}} MS

							Total HTTP requests:
							{{formatNumber(stats.cdn.percdn[stats.cedexis.bestcdnspeed[2][0]])}}

						TOTAL CDN STATS

						(last 30 days / Last update: {{formatDate(stats.lastUpdate)}})

							LOAD BALANCING DECISIONS

{{formatNumber(stats.cedexis.total)}}

							HTTP HITS

{{formatNumber(stats.cdn.total.hits)}}

{{Math.floor(stats.cdn.total.traffic / 1024 / 1024 / 1024 / 1024)}}TB SERVED

							DNS REQUESTS

{{formatNumber(stats.dns.total)}}

Load Balancing decisions

DNS requests

							Load Balancing decisions map

							Performance map

							Based on tens of millions of RUM tests for the last 24 hours

		{{/if !stats}}


text:
/* $Id$ */

/*
 * Copyright (c) 2010-2011 SURFnet bv
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of SURFnet bv nor the names of its contributors
 *    may be used to endorse or promote products derived from this
 *    software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
 * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
 * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

/*
 * The Extensible Ethernet Monitor (EEMO)
 */

#include "config.h"
#include "eemo.h"
#include "eemo_log.h"
#include "eemo_blacklist.h"
#include <string.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include "uthash.h"
#include "dns_parser.c"

/* This is a structure that can be hashed,
 * it is used to store blacklisted elements */
struct hashstructure
{
	char *hashelement;
	UT_hash_handle hh;         /* makes this structure hashable */
};

/* Configuration */
int	blacklist_mod    = 0;
char*	logging_file_name		= NULL;
FILE*	logging_file			= NULL;
struct	hashstructure *hashtable 	= NULL;    /* important! initialize the HASH TABLE */
int	testcount 			= 0;
char*	temp_answer			= NULL;

/* Convert the rdata of a DNS answer that contains an IP address to string. */
void qtypeA_to_string ( eemo_dns_rr* rr, char* rv )
{
	snprintf ( rv, 16, "%d.%d.%d.%d",
	           ( * ( ( unsigned int* ) rr->rdata ) & 0xff000000 ) >> 24,
	           ( * ( ( unsigned int* ) rr->rdata ) & 0x00ff0000 ) >> 16,
	           ( * ( ( unsigned int* ) rr->rdata ) & 0x0000ff00 ) >> 8,
	           ( * ( ( unsigned int* ) rr->rdata ) & 0x000000ff ) );
}

/* Initialize the module */
short eemo_blacklist_initialize ( int temp_blacklist_mod, char* blacklist_file_name, char* temp_logging_file_name )
{
	// Variables used to read and load the blacklist file.
	FILE * blacklist_file 	= NULL;
	char * line 		= NULL;
	size_t line_length 	= 0;
	ssize_t read;

	logging_file_name = temp_logging_file_name;
	blacklist_mod = temp_blacklist_mod;

	/* If an IP-based blacklist is used, a variable to temporarily store
	 * the IP address of every DNS answer in needed. */
	if ( blacklist_mod == 1 )
	{
		temp_answer = ( char* ) malloc ( 16 * sizeof ( char ) ); /* 4x 3 digits + 3x '.' + \0 */
	}

	// Open the log file.
	logging_file = fopen ( logging_file_name, "w" );
	if ( logging_file == NULL )
	{
		ERROR_MSG ( "Failed to open '%s' for writing", logging_file_name );
		return 0;
	}
	INFO_MSG ( "Writing infected nodes to: '%s'", logging_file_name );

	// Open the file that contains the malicious elements.
	blacklist_file = fopen ( blacklist_file_name, "r" );
	if ( blacklist_file == NULL )
	{
		ERROR_MSG ( "Failed to open '%s' for reading", blacklist_file_name );
		return 0;
	}

	// Total number of loaded blacklisted elements.
	int sum_loaded_elements = 0;

	// Read the file and insert the malicious elements to the hash table.
	while ( ( read = getline ( &line, &line_length, blacklist_file ) ) != -1 )
	{
		// Remove the newline character at the end of each line.
		line[strcspn ( line, "\r\n" )] = 0;

		// Allocate memory for each element.
		char *tempelement;
		tempelement = ( char * ) malloc ( sizeof ( char ) * line_length );
		strncpy ( tempelement, line, line_length );

		// Check if the value is already inserted in the hash table.
		struct hashstructure *s;
		HASH_FIND_STR ( hashtable, tempelement, s );
		if ( s != NULL )
		{
			ERROR_MSG ( "collision between '%s' AND '%s'", line, s->hashelement );
			ERROR_MSG ( "Verify that '%s' does not contain dublicate entries", blacklist_file_name );
			/* blacklists regularly do not contain duplicate entries and the file might
			 * be corrupted. However, the termination can be safely removed. */
			return 0;
		}
		else
		{
			// Insert the blacklisted element to the hash table.
			struct hashstructure *d;
			d = ( struct hashstructure* ) malloc ( sizeof ( struct hashstructure ) );
			d->hashelement = tempelement;
			HASH_ADD_KEYPTR ( hh, hashtable, d->hashelement, strlen ( d->hashelement ), d );

			sum_loaded_elements++;
		}
	}

	// Verify that the file is still open and close it.
	if ( blacklist_file == NULL )
	{
		ERROR_MSG ( "File '%s' has closed unexpectedly", blacklist_file_name );
		return 0;
	}
	fclose ( blacklist_file );
	INFO_MSG ( "%d blacklisted elements were loaded successfully", sum_loaded_elements );
	return 1;
}

/* Uninitialize the DNS query counter module */
void eemo_blacklist_uninitialize ( eemo_conf_free_string_array_fn free_strings )
{
	fprintf ( logging_file, "Total inspected packets: %d\n", testcount );

	// Verify that the file is still open and close it.
	if ( logging_file == NULL )
	{
		ERROR_MSG ( "File '%s' has closed unexpectedly", logging_file_name );
	}
	fclose ( logging_file );

	// Free the memory of the hash table.
	struct hashstructure *current, *tmp;
	HASH_ITER ( hh, hashtable, current, tmp )
	{
		HASH_DEL ( hashtable, current ); /* delete it (users advances to next) */
		free ( current->hashelement );
		free ( current );
	}
	free ( logging_file_name );
	free ( temp_answer );
}

/* Handle DNS query packets and log the blacklisted elements*/
eemo_rv eemo_blacklist_handleqr ( eemo_ip_packet_info ip_info, int is_tcp, const eemo_dns_packet* dns_packet )
{
	testcount++;

	// Check if the packet is a query and
	if ( !dns_packet->qr_flag )
	{
		// Verify that a domain-based blacklist is used.
		if ( blacklist_mod == 0 )
		{
			// Validate the packet
			if ( !dns_packet->is_valid )
			{
				return ERV_SKIPPED;
			}

			if ( logging_file == NULL )
			{
				ERROR_MSG ( "File '%s' has closed unexpectedly", logging_file_name );
			}

			// Iterate for every requested domain in the query.
			eemo_dns_query* query_it = NULL;
			LL_FOREACH ( dns_packet->questions, query_it )
			{
				// Check if the domain is in the blacklist.
				struct hashstructure *s; // s: output pointer
				HASH_FIND_STR ( hashtable, query_it->qname, s );
				if ( s != NULL )
				{
					fprintf ( logging_file, "query for blacklisted domain: %s , from %s\n", query_it->qname, ip_info.ip_src );
					break;
				}
				//fflush(logging_file);
			}
		}
	}
	else
	{
		// Verify that an IP-based blacklist is used.
		if ( blacklist_mod == 1 )
		{
			// Validate the packet
			if ( !dns_packet->is_valid )
			{
				return ERV_SKIPPED;
			}

			if ( logging_file == NULL )
			{
				ERROR_MSG ( "File '%s' has closed unexpectedly", logging_file_name );
			}

			if ( dns_packet->answers != NULL )
			{
				// Iterate for every RR in the DNS answer.
				eemo_dns_rr* temp_rr;
				LL_FOREACH ( dns_packet->answers, temp_rr )
				{
					if ( temp_rr->type == DNS_QTYPE_A )
					{
						struct hashstructure *s; // s: output pointer
						temp_answer[0] = '\0';
						qtypeA_to_string ( temp_rr, temp_answer );
						if ( temp_answer[0] == '\0' )
						{
							DEBUG_MSG ( "Answer is empty" );
						}
						else
						{
							// Check if the IP is in the blacklist.
							HASH_FIND_STR ( hashtable, temp_answer, s );
							if ( s != NULL )
							{
								fprintf ( logging_file, "query for blacklisted IP: \"%s\", from: \"%s\"\n", temp_answer, ip_info.ip_src );
								DEBUG_MSG ( "Malicious answer: \"%s\"", temp_answer );
							}
						}
					}
				}
				//fflush(logging_file);
			}
		}
	}
	return ERV_HANDLED;
}


text:
using System.Net.Http;
using System.Threading.Tasks;
using Tweetinvi.Parameters;
using Xunit;
using Xunit.Abstractions;
using xUnitinvi.TestHelpers;

namespace xUnitinvi.EndToEnd
{
    [Collection("EndToEndTests")]
    public class UploadEndToEndTests : TweetinviTest
    {
        public UploadEndToEndTests(ITestOutputHelper logger) : base(logger)
        {
        }

        [Fact]
        public async Task UploadVideoAsync()
        {
            if (!EndToEndTestConfig.ShouldRunEndToEndTests)
                return;

            var httpClient = new HttpClient();

            _logger.WriteLine("Downloading video...");
            var videoBinary = await httpClient.GetByteArrayAsync("https://github.com/linvi/tweetinvi.issues/raw/master/sample_video.mp4");
            _logger.WriteLine("Video downloaded");

            var uploadedVideo = await _tweetinviTestClient.Upload.UploadTweetVideoAsync(videoBinary);
            await _tweetinviTestClient.Upload.WaitForMediaProcessingToGetAllMetadataAsync(uploadedVideo);

            var tweet = await _tweetinviTestClient.Tweets.PublishTweetAsync(new PublishTweetParameters("superb video...")
            {
                Medias = {uploadedVideo}
            });

            await tweet.DestroyAsync();

            Assert.Equal(tweet.Media.Count, 1);
        }
    }
}


text:
package org.kantega.reststop.maven;

import org.kantega.reststop.classloaderutils.config.PluginConfigParams;

/**
 *
 */
public class PluginConfig  {

    private final String className;

    private final PluginConfigParams configParams;

    public PluginConfig(String className, PluginConfigParams configParams) {
        this.className = className;
        this.configParams = configParams;
    }

    public String getClassName() {
        return className;
    }

    public PluginConfigParams getConfigParams() {
        return configParams;
    }
}


text:
#include <stdlib.h>
#include "CppUTest/TestHarness.h"
#undef malloc
#undef free
#undef calloc
#undef realloc
#undef strdup
#undef strndup

#include <sys/time.h>
#include <time.h>
#include <stdio.h>
#include <stdarg.h>
#include <setjmp.h>
#include <string.h>
#include <math.h>
#include <ctype.h>
#include <unistd.h>
#include <signal.h>
#ifndef __MINGW32__
#include <sys/wait.h>
#include <errno.h>
#endif
#include <pthread.h>

#include "CppUTest/PlatformSpecificFunctions.h"

static jmp_buf test_exit_jmp_buf[10];
static int jmp_buf_index = 0;

#ifndef CPPUTEST_HAVE_FORK

static void GccPlatformSpecificRunTestInASeperateProcess(UtestShell* shell, TestPlugin*, TestResult* result)
{
    result->addFailure(TestFailure(shell, "-p doesn't work on this platform, as it is lacking fork.\b"));
}

static int PlatformSpecificForkImplementation(void)
{
    return 0;
}

static int PlatformSpecificWaitPidImplementation(int, int*, int)
{
    return 0;
}

#else

static void GccPlatformSpecificRunTestInASeperateProcess(UtestShell* shell, TestPlugin* plugin, TestResult* result)
{
    pid_t cpid, w;
    int status;

    cpid = PlatformSpecificFork();

    if (cpid == -1) {
        result->addFailure(TestFailure(shell, "Call to fork() failed"));
        return;
    }

    if (cpid == 0) {            /* Code executed by child */
        shell->runOneTestInCurrentProcess(plugin, *result);   // LCOV_EXCL_LINE
        _exit(result->getFailureCount());                     // LCOV_EXCL_LINE
    } else {                    /* Code executed by parent */
        do {
            w = PlatformSpecificWaitPid(cpid, &status, WUNTRACED);
            if (w == -1) {
                if(EINTR ==errno) continue; /* OS X debugger */
                result->addFailure(TestFailure(shell, "Call to waitpid() failed"));
                return;
            }

            if (WIFEXITED(status) && WEXITSTATUS(status) > result->getFailureCount()) {
                result->addFailure(TestFailure(shell, "Failed in separate process"));
            } else if (WIFSIGNALED(status)) {
                SimpleString signal(StringFrom(WTERMSIG(status)));
                {
                    SimpleString message("Failed in separate process - killed by signal ");
                    message += signal;
                    result->addFailure(TestFailure(shell, message));
                }
            } else if (WIFSTOPPED(status)) {
                result->addFailure(TestFailure(shell, "Stopped in separate process - continuing"));
                kill(w, SIGCONT);
            }
        } while (!WIFEXITED(status) && !WIFSIGNALED(status));
    }
}

static pid_t PlatformSpecificForkImplementation(void)
{
    return fork();
}

static pid_t PlatformSpecificWaitPidImplementation(int pid, int* status, int options)
{
    return waitpid(pid, status, options);
}

#endif

TestOutput::WorkingEnvironment PlatformSpecificGetWorkingEnvironment()
{
    return TestOutput::eclipse;
}

void (*PlatformSpecificRunTestInASeperateProcess)(UtestShell* shell, TestPlugin* plugin, TestResult* result) =
        GccPlatformSpecificRunTestInASeperateProcess;
int (*PlatformSpecificFork)(void) = PlatformSpecificForkImplementation;
int (*PlatformSpecificWaitPid)(int, int*, int) = PlatformSpecificWaitPidImplementation;

extern "C" {

static int PlatformSpecificSetJmpImplementation(void (*function) (void* data), void* data)
{
    if (0 == setjmp(test_exit_jmp_buf[jmp_buf_index])) {
        jmp_buf_index++;
        function(data);
        jmp_buf_index--;
        return 1;
    }
    return 0;
}

/*
 * MacOSX clang 3.0 doesn't seem to recognize longjmp and thus complains about __no_return_.
 * The later clang compilers complain when it isn't there. So only way is to check the clang compiler here :(
 */
#if !((__clang_major__ == 3) && (__clang_minor__ == 0))
__no_return__
#endif
static void PlatformSpecificLongJmpImplementation()
{
    jmp_buf_index--;
    longjmp(test_exit_jmp_buf[jmp_buf_index], 1);
}

static void PlatformSpecificRestoreJumpBufferImplementation()
{
    jmp_buf_index--;
}

void (*PlatformSpecificLongJmp)() = PlatformSpecificLongJmpImplementation;
int (*PlatformSpecificSetJmp)(void (*)(void*), void*) = PlatformSpecificSetJmpImplementation;
void (*PlatformSpecificRestoreJumpBuffer)() = PlatformSpecificRestoreJumpBufferImplementation;

///////////// Time in millis

static long TimeInMillisImplementation()
{
    struct timeval tv;
    struct timezone tz;
    gettimeofday(&tv, &tz);
    return (tv.tv_sec * 1000) + (long)((double)tv.tv_usec * 0.001);
}

static const char* TimeStringImplementation()
{
    time_t tm = time(NULLPTR);
    static char dateTime[80];
    struct tm *tmp = localtime(&tm);
    strftime(dateTime, 80, "%Y-%m-%dT%H:%M:%S", tmp);
    return dateTime;
}

long (*GetPlatformSpecificTimeInMillis)() = TimeInMillisImplementation;
const char* (*GetPlatformSpecificTimeString)() = TimeStringImplementation;

/* Wish we could add an attribute to the format for discovering mis-use... but the __attribute__(format) seems to not work on va_list */
#ifdef __clang__
#pragma clang diagnostic ignored "-Wformat-nonliteral"
#endif

#ifdef __clang__
#pragma clang diagnostic ignored "-Wused-but-marked-unused"
#endif
int (*PlatformSpecificVSNprintf)(char *str, size_t size, const char* format, va_list va_args_list) = vsnprintf;

static PlatformSpecificFile PlatformSpecificFOpenImplementation(const char* filename, const char* flag)
{
   return fopen(filename, flag);
}

static void PlatformSpecificFPutsImplementation(const char* str, PlatformSpecificFile file)
{
   fputs(str, (FILE*)file);
}

static void PlatformSpecificFCloseImplementation(PlatformSpecificFile file)
{
   fclose((FILE*)file);
}

static void PlatformSpecificFlushImplementation()
{
  fflush(stdout);
}

PlatformSpecificFile (*PlatformSpecificFOpen)(const char*, const char*) = PlatformSpecificFOpenImplementation;
void (*PlatformSpecificFPuts)(const char*, PlatformSpecificFile) = PlatformSpecificFPutsImplementation;
void (*PlatformSpecificFClose)(PlatformSpecificFile) = PlatformSpecificFCloseImplementation;

int (*PlatformSpecificPutchar)(int) = putchar;
void (*PlatformSpecificFlush)() = PlatformSpecificFlushImplementation;

void* (*PlatformSpecificMalloc)(size_t size) = malloc;
void* (*PlatformSpecificRealloc)(void*, size_t) = realloc;
void (*PlatformSpecificFree)(void* memory) = free;
void* (*PlatformSpecificMemCpy)(void*, const void*, size_t) = memcpy;
void* (*PlatformSpecificMemset)(void*, int, size_t) = memset;

/* GCC 4.9.x introduces -Wfloat-conversion, which causes a warning / error
 * in GCC's own (macro) implementation of isnan() and isinf().
 */
#if defined(__GNUC__) && (__GNUC__ >= 5 || (__GNUC__ == 4 && __GNUC_MINOR__ > 8))
#pragma GCC diagnostic ignored "-Wfloat-conversion"
#endif

static int IsNanImplementation(double d)
{
    return isnan(d);
}

static int IsInfImplementation(double d)
{
    return isinf(d);
}

double (*PlatformSpecificFabs)(double) = fabs;
int (*PlatformSpecificIsNan)(double) = IsNanImplementation;
int (*PlatformSpecificIsInf)(double) = IsInfImplementation;
int (*PlatformSpecificAtExit)(void(*func)(void)) = atexit;  /// this was undefined before

static PlatformSpecificMutex PThreadMutexCreate(void)
{
    pthread_mutex_t *mutex = new pthread_mutex_t;

    pthread_mutex_init(mutex, NULLPTR);

    return (PlatformSpecificMutex)mutex;
}

static void PThreadMutexLock(PlatformSpecificMutex mtx)
{
    pthread_mutex_lock((pthread_mutex_t *)mtx);
}

static void PThreadMutexUnlock(PlatformSpecificMutex mtx)
{
    pthread_mutex_unlock((pthread_mutex_t *)mtx);
}

static void PThreadMutexDestroy(PlatformSpecificMutex mtx)
{
    pthread_mutex_t *mutex = (pthread_mutex_t *)mtx;
    pthread_mutex_destroy(mutex);
    delete mutex;
}

PlatformSpecificMutex (*PlatformSpecificMutexCreate)(void) = PThreadMutexCreate;
void (*PlatformSpecificMutexLock)(PlatformSpecificMutex) = PThreadMutexLock;
void (*PlatformSpecificMutexUnlock)(PlatformSpecificMutex) = PThreadMutexUnlock;
void (*PlatformSpecificMutexDestroy)(PlatformSpecificMutex) = PThreadMutexDestroy;

}


text:
/**
 *
 */
package cern.accsoft.steering.aloha.bean.aware;

import cern.accsoft.steering.aloha.bean.AlohaBeanFactory;

/**
 * This is the interface of a class that uses a {@link AlohaBeanFactory}
 * itself.
 *
 * @author kfuchsbe
 *
 */
public interface AlohaBeanFactoryAware extends BeanAware {

	/**
	 * this method is used by the {@link AlohaBeanFactory} to inject itself.
	 *
	 * @param alohaBeanFactory
	 */
	public void setAlohaBeanFactory(AlohaBeanFactory alohaBeanFactory);
}


text:
package com.wustrive.aesrsa.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

import org.apache.log4j.Logger;

public class Digest {
	private static final Logger log = Logger.getLogger(Digest.class);
	public static final String ENCODE = "UTF-8";

	public static String signMD5(String aValue, String encoding) {
		try {
			byte[] input = aValue.getBytes(encoding);
			MessageDigest md = MessageDigest.getInstance("MD5");
			return ConvertUtils.toHex(md.digest(input));
		} catch (NoSuchAlgorithmException e) {
			log.error(e.getMessage(), e);
			return null;
		} catch (UnsupportedEncodingException e) {
			log.error(e.getMessage(), e);
			return null;
		}
	}

	public static String hmacSign(String aValue) {
		try {
			byte[] input = aValue.getBytes();
			MessageDigest md = MessageDigest.getInstance("MD5");
			return ConvertUtils.toHex(md.digest(input));
		} catch (NoSuchAlgorithmException e) {
			log.error(e.getMessage(), e);
			return null;
		}
	}

	public static String hmacSign(String aValue, String aKey) {
		return hmacSign(aValue, aKey, ENCODE);
	}

	public static String hmacSign(String aValue, String aKey, String encoding) {
		byte k_ipad[] = new byte[64];
		byte k_opad[] = new byte[64];
		byte keyb[];
		byte value[];
		try {
			keyb = aKey.getBytes(encoding);
			value = aValue.getBytes(encoding);
		} catch (UnsupportedEncodingException e) {
			keyb = aKey.getBytes();
			value = aValue.getBytes();
		}
		Arrays.fill(k_ipad, keyb.length, 64, (byte) 54);
		Arrays.fill(k_opad, keyb.length, 64, (byte) 92);
		for (int i = 0; i < keyb.length; i++) {
			k_ipad[i] = (byte) (keyb[i] ^ 0x36);
			k_opad[i] = (byte) (keyb[i] ^ 0x5c);
		}

		MessageDigest md = null;
		try {
			md = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e) {
			log.error(e.getMessage(), e);
			return null;
		}
		md.update(k_ipad);
		md.update(value);
		byte dg[] = md.digest();
		md.reset();
		md.update(k_opad);
		md.update(dg, 0, 16);
		dg = md.digest();
		return ConvertUtils.toHex(dg);
	}

	public static String hmacSHASign(String aValue, String aKey, String encoding) {
		byte k_ipad[] = new byte[64];
		byte k_opad[] = new byte[64];
		byte keyb[];
		byte value[];
		try {
			keyb = aKey.getBytes(encoding);
			value = aValue.getBytes(encoding);
		} catch (UnsupportedEncodingException e) {
			keyb = aKey.getBytes();
			value = aValue.getBytes();
		}
		Arrays.fill(k_ipad, keyb.length, 64, (byte) 54);
		Arrays.fill(k_opad, keyb.length, 64, (byte) 92);
		for (int i = 0; i < keyb.length; i++) {
			k_ipad[i] = (byte) (keyb[i] ^ 0x36);
			k_opad[i] = (byte) (keyb[i] ^ 0x5c);
		}

		MessageDigest md = null;
		try {
			md = MessageDigest.getInstance("SHA");
		} catch (NoSuchAlgorithmException e) {
			log.error(e.getMessage(), e);
			return null;
		}
		md.update(k_ipad);
		md.update(value);
		byte dg[] = md.digest();
		md.reset();
		md.update(k_opad);
		md.update(dg, 0, 20);
		dg = md.digest();
		return ConvertUtils.toHex(dg);
	}

	public static String digest(String aValue) {
		return digest(aValue, ENCODE);

	}

	public static String digest(String aValue, String encoding) {
		aValue = aValue.trim();
		byte value[];
		try {
			value = aValue.getBytes(encoding);
		} catch (UnsupportedEncodingException e) {
			value = aValue.getBytes();
		}
		MessageDigest md = null;
		try {
			md = MessageDigest.getInstance("SHA");
		} catch (NoSuchAlgorithmException e) {
			log.error(e.getMessage(), e);
			return null;
		}
		return ConvertUtils.toHex(md.digest(value));
	}

	public static String digest(String aValue, String alg, String encoding) {
		aValue = aValue.trim();
		byte value[];
		try {
			value = aValue.getBytes(encoding);
		} catch (UnsupportedEncodingException e) {
			value = aValue.getBytes();
		}
		MessageDigest md = null;
		try {
			md = MessageDigest.getInstance(alg);
		} catch (NoSuchAlgorithmException e) {
			log.error(e.getMessage(), e);
			return null;
		}
		return ConvertUtils.toHex(md.digest(value));
	}

	public static String udpSign(String aValue) {
		try {
			byte[] input = aValue.getBytes("UTF-8");
			MessageDigest md = MessageDigest.getInstance("SHA1");
			return new String(Base64.encode(md.digest(input)), ENCODE);
		} catch (Exception e) {
			return null;
		}
	}

}


text:
using CONFIG4CPP_NAMESPACE::Configuration;
using CONFIG4CPP_NAMESPACE::ConfigurationException;
using CONFIG4CPP_NAMESPACE::SchemaValidator;
using CONFIG4CPP_NAMESPACE::StringBuffer;
using CONFIG4CPP_NAMESPACE::StringVector;

//--------
// Forward declarations
//--------
static void usage(const char * optMsg);

static void parseCmdLineArgs(
	int								argc,
	char **							argv,
	const char *&					cmd,
	bool &							isRecursive,
	bool &							wantExpandedUidNames,
	StringVector &					filterPatterns,
	const char *&					scope,
	const char *&					name,
	const char *&					cfgSource,
	const char *&					secSource,
	const char *&					secScope,
	const char *&					schemaSource,
	const char *&					schemaName,
	SchemaValidator::ForceMode &	forceMode,
	bool &							wantDiagnostics,
	Configuration::Type &			types,
	Configuration *					cfg);

static Configuration::Type stringToTypes(const char * str);

int
main(int argc, char ** argv)
{
	const char *				cmd;
	bool						isRecursive;
	bool						wantExpandedUidNames;
	StringVector				filterPatterns;
	const char *				scope;
	const char *				name;
	const char *				cfgSource;
	const char *				secSource;
	const char *				secScope;
	const char *				schemaSource;
	const char *				schemaName;
	bool						wantDiagnostics;
	const char *				str;
	Configuration *				cfg;
	Configuration *				secCfg;
	Configuration *				schemaCfg;
	const Configuration *		secDumpCfg;
	const char *				secDumpScope;
	const char **				vec;
	int							len;
	const char **				schemaVec;
	int							schemaLen;
	SchemaValidator::ForceMode	forceMode;
	int							i;
	StringBuffer				buf;
	StringVector				names;
	StringBuffer				fullyScopedName;
	Configuration::Type			types;
	SchemaValidator				sv;

	setlocale(LC_ALL, "");

	cfg       = Configuration::create();
	secCfg    = Configuration::create();
	schemaCfg = Configuration::create();

	parseCmdLineArgs(argc, argv, cmd, isRecursive, wantExpandedUidNames,
                     filterPatterns, scope, name, cfgSource, secSource,
	                 secScope, schemaSource, schemaName, forceMode,
	                 wantDiagnostics, types, cfg);

	try {
		if (secSource != 0) {
			secCfg->parse(secSource);
			cfg->setSecurityConfiguration(secCfg, secScope);
		}
		cfg->parse(cfgSource);
	} catch (const ConfigurationException & ex) {
		printf("%s\n", ex.c_str());
		exit(1);
	}
	cfg->mergeNames(scope, name, fullyScopedName);

	if (strcmp(cmd, "parse") == 0) {
		//--------
		// Nothing else to do
		//--------
	} else if (strcmp(cmd, "validate") == 0) {
		try {
			schemaCfg->parse(schemaSource);
			schemaCfg->lookupList(schemaName, "", schemaVec, schemaLen);
			sv.wantDiagnostics(wantDiagnostics);
			sv.parseSchema(schemaVec, schemaLen);
			sv.validate(cfg, scope, name, isRecursive, types, forceMode);
		} catch (ConfigurationException & ex) {
			fprintf(stderr, "%s\n", ex.c_str());
		}
	} else if (strcmp(cmd, "slist") == 0) {
		try {
			cfg->listFullyScopedNames(scope, name, types, isRecursive,
			                          filterPatterns, names);
			len = names.length();
			for (i = 0; i < len; i++) {
				printf("%s\n", names[i]);
			}
		} catch (ConfigurationException & ex) {
			fprintf(stderr, "%s\n", ex.c_str());
		}
	} else if (strcmp(cmd, "llist") == 0) {
		try {
			cfg->listLocallyScopedNames(scope, name, types, isRecursive,
			                            filterPatterns, names);
			len = names.length();
			for (i = 0; i < len; i++) {
				printf("%s\n", names[i]);
			}
		} catch (ConfigurationException & ex) {
			fprintf(stderr, "%s\n", ex.c_str());
		}
	} else if (strcmp(cmd, "type") == 0) {
		switch (cfg->type(scope, name)) {
		case Configuration::CFG_STRING:
			printf("string\n");
			break;
		case Configuration::CFG_LIST:
			printf("list\n");
			break;
		case Configuration::CFG_SCOPE:
			printf("scope\n");
			break;
		case Configuration::CFG_NO_VALUE:
			printf("no_value\n");
			break;
		default:
			assert(0); // Bug!
			break;
		}
	} else if (strcmp(cmd, "print") == 0) {
		try {
			switch (cfg->type(scope, name)) {
			case Configuration::CFG_STRING:
				str = cfg->lookupString(scope, name);
				printf("%s\n", str);
				break;
			case Configuration::CFG_LIST:
				cfg->lookupList(scope, name, vec, len);
				for (i = 0; i < len; i++) {
					printf("%s\n", vec[i]);
				}
				break;
			case Configuration::CFG_SCOPE:
				fprintf(stderr, "'%s' is a scope\n",
					fullyScopedName.c_str());
				break;
			case Configuration::CFG_NO_VALUE:
				fprintf(stderr, "'%s' does not exist\n",
					fullyScopedName.c_str());
				break;
			default:
				assert(0); // Bug!
				break;
			}
		} catch(const ConfigurationException & ex) {
			fprintf(stderr, "%s\n", ex.c_str());
		}
	} else if (strcmp(cmd, "dumpSec") == 0) {
		try {
			cfg->getSecurityConfiguration(secDumpCfg, secDumpScope);
			secDumpCfg->dump(buf, wantExpandedUidNames, secDumpScope,
			                 "allow_patterns");
			printf("%s", buf.c_str());
			secDumpCfg->dump(buf, wantExpandedUidNames, secDumpScope,
			                 "deny_patterns");
			printf("%s", buf.c_str());
			secDumpCfg->dump(buf, wantExpandedUidNames, secDumpScope,
			                 "trusted_directories");
			printf("%s", buf.c_str());
		} catch(const ConfigurationException & ex) {
			fprintf(stderr, "%s\n", ex.c_str());
		}
	} else if (strcmp(cmd, "dump") == 0) {
		try {
			cfg->dump(buf, wantExpandedUidNames, scope, name);
			printf("%s", buf.c_str());
		} catch(const ConfigurationException & ex) {
			fprintf(stderr, "%s\n", ex.c_str());
		}
	} else {
		assert(0); // Bug!
	}

	//--------
	// Terminate gracefully
	//--------
	cfg->destroy();
	secCfg->destroy();
	schemaCfg->destroy();
	return 0;
}

static void
parseCmdLineArgs(
	int								argc,
	char **							argv,
	const char *&					cmd,
	bool &							isRecursive,
	bool &							wantExpandedUidNames,
	StringVector &					filterPatterns,
	const char *&					scope,
	const char *&					name,
	const char *&					cfgSource,
	const char *&					secSource,
	const char *&					secScope,
	const char *&					schemaSource,
	const char *&					schemaName,
	SchemaValidator::ForceMode &	forceMode,
	bool &							wantDiagnostics,
	Configuration::Type &			types,
	Configuration *					cfg)
{
	int								i;
	StringBuffer					msg;

	cmd = 0;
	wantExpandedUidNames = true;
	scope = "";
	name = "";
	cfgSource = 0;
	secSource = 0;
	secScope  = "";
	schemaSource = 0;
	schemaName = 0;
	wantDiagnostics = false;
	forceMode = SchemaValidator::DO_NOT_FORCE;
	isRecursive = true;
	types = Configuration::CFG_SCOPE_AND_VARS;
	filterPatterns.empty();

	for (i = 1; i < argc; i++) {
		if (strcmp(argv[i], "-h") == 0) {
			usage("");
		} else if (strcmp(argv[i], "-set") == 0) {
			if (i >= argc-2) { usage(""); }
			cfg->insertString("", argv[i+1], argv[i+2]);
			i += 2;
		} else if (strcmp(argv[i], "-cfg") == 0) {
			if (i == argc-1) { usage(""); }
			cfgSource = argv[i+1];
			i++;
		} else if (strcmp(argv[i], "-secCfg") == 0) {
			if (i == argc-1) { usage(""); }
			secSource = argv[i+1];
			i++;
		} else if (strcmp(argv[i], "-secScope") == 0) {
			if (i == argc-1) { usage(""); }
			secScope = argv[i+1];
			i++;
		} else if (strcmp(argv[i], "-schemaCfg") == 0) {
			if (i == argc-1) { usage(""); }
			schemaSource = argv[i+1];
			i++;
		} else if (strcmp(argv[i], "-schema") == 0) {
			if (i == argc-1) { usage(""); }
			schemaName = argv[i+1];
			i++;
		} else if (strcmp(argv[i], "-diagnostics") == 0) {
			wantDiagnostics = true;
		} else if (strcmp(argv[i], "-force_optional") == 0) {
			forceMode = SchemaValidator::FORCE_OPTIONAL;
		} else if (strcmp(argv[i], "-force_required") == 0) {
			forceMode = SchemaValidator::FORCE_REQUIRED;
		} else if (strcmp(argv[i], "-nodiagnostics") == 0) {
			wantDiagnostics = true;
		} else if (strcmp(argv[i], "-types") == 0) {
			if (i == argc-1) { usage(""); }
			types = stringToTypes(argv[i+1]);
			i++;
		//--------
		// Commands
		//--------
		} else if (strcmp(argv[i], "parse") == 0) {
			cmd = argv[i];
		} else if (strcmp(argv[i], "slist") == 0) {
			cmd = argv[i];
		} else if (strcmp(argv[i], "llist") == 0) {
			cmd = argv[i];
		} else if (strcmp(argv[i], "dump") == 0) {
			cmd = argv[i];
		} else if (strcmp(argv[i], "dumpSec") == 0) {
			cmd = argv[i];
		} else if (strcmp(argv[i], "type") == 0) {
			cmd = argv[i];
		} else if (strcmp(argv[i], "print") == 0) {
			cmd = argv[i];
		} else if (strcmp(argv[i], "validate") == 0) {
			cmd = argv[i];
		//--------
		// Arguments to commands
		//--------
		} else if (strcmp(argv[i], "-scope") == 0) {
			if (i == argc-1) { usage(""); }
			scope = argv[i+1];
			i++;
		} else if (strcmp(argv[i], "-filter") == 0) {
			if (i == argc-1) { usage(""); }
			filterPatterns.add(argv[i+1]);
			i++;
		} else if (strcmp(argv[i], "-name") == 0) {
			if (i == argc-1) { usage(""); }
			name = argv[i+1];
			i++;
		} else if (strcmp(argv[i], "-recursive") == 0) {
			isRecursive = true;
		} else if (strcmp(argv[i], "-norecursive") == 0) {
			isRecursive = false;
		} else if (strcmp(argv[i], "-expandUid") == 0) {
			wantExpandedUidNames = true;
		} else if (strcmp(argv[i], "-unexpandUid") == 0) {
			wantExpandedUidNames = false;
		} else {
			usage(argv[i]);
		}
	}
	if (cfgSource == 0) {
		fprintf(stderr, "\nYou must specify -cfg <source>\n\n");
		usage("");
	}
	if (cmd == 0) {
		fprintf(stderr, "\nYou must specify a command\n\n");
		usage("");
	}
	if (strcmp(cmd, "validate") == 0) {
		if (schemaSource == 0) {
			fprintf(stderr, "\nThe validate command requires "
					"-schemaCfg <source>\n\n");
			usage("");
		}
		if (schemaName == 0) {
			fprintf(stderr, "\nThe validate command requires "
					"-schema <full.name>\n\n");
			usage("");
		}
	}
}

static Configuration::Type stringToTypes(const char * str)
{
	if (strcmp(str, "string") == 0) {
		return Configuration::CFG_STRING;
	} else if (strcmp(str, "list") == 0) {
		return Configuration::CFG_LIST;
	} else if (strcmp(str, "scope") == 0) {
		return Configuration::CFG_SCOPE;
	} else if (strcmp(str, "variables") == 0) {
		return Configuration::CFG_VARIABLES;
	} else if (strcmp(str, "scope_and_vars") == 0) {
		return Configuration::CFG_SCOPE_AND_VARS;
	}
	usage("Invalid value for '-types <...>'");
	return Configuration::CFG_STRING; // Not reached; keep compiler happy
}

static void
usage(const char * optMsg)
{
	StringBuffer			msg;

	if (strcmp(optMsg, "") != 0) {
		msg << optMsg << "\n\n";
	}

	msg << "usage: config4cpp -cfg <source> <command> <options>\n"
	    << "\n"
	    << "<command> can be one of the following:\n"
	    << "  parse               Parse and report errors, if any\n"
	    << "  validate            Validate <scope>.<name>\n"
	    << "  dump                Dump <scope>.<name>\n"
	    << "  dumpSec             Dump the security policy\n"
	    << "  print               Print value of the <scope>.<name> "
	    <<								"variable\n"
	    << "  type                Print type of the <scope>.<name> entry\n"
	    << "  slist               List scoped names in <scope>.<name>\n"
	    << "  llist               List local names in <scope>.<name>\n"
	    << "\n"
	    << "<options> can be:\n"
	    << "  -h                  Print this usage statement\n"
	    << "  -set <name> <value> Preset name=value in configuration object\n"
	    << "  -scope <scope>      Specify <scope> argument for commands\n"
	    << "  -name <name>        Specify <name> argument for commands\n"
	    << "\n"
	    << "  -secCfg <source>    Override default security policy\n"
	    << "  -secScope <scope>   Scope for security policy\n"
	    << "\n"
	    << "  -schemaCfg <source> Source that contains a schema\n"
	    << "  -schema <full.name> Name of schema in '-schemaCfg <source>'\n"
	    << "  -force_optional     Validate with forceMode = "
	    <<				"FORCE_OPTIONAL\n"
	    << "  -force_required     Validate with forceMode = "
	    <<				"FORCE_REQUIRED\n"
	    << "  -diagnostics        Print diagnostics during schema "
	    <<				"validation\n"
	    << "  -nodiagnostics      Do not print diagnostics during schema "
	    <<				"validation (default)\n"
	    << "\n"
	    << "  -recursive          For llist, slist and validate (default)\n"
	    << "  -norecursive        For llist, slist and validate\n"
	    << "  -filter <pattern>   A filter pattern for slist and llist\n"
	    << "  -types <types>      For llist, slist and validate\n"
	    << "\n"
	    << "  -expandUid          For dump (default)\n"
	    << "  -unexpandUid        For dump\n"
	    << "\n"
	    << "<types> can be one of the following:\n"
	    << "  string, list, scope, variables, scope_and_vars (default)\n"
	    << "\n"
	    << "<source> can be one of the following:\n"
	    << "  file.cfg       A configuration file\n"
	    << "  file#file.cfg  A configuration file\n"
	    << "  exec#<command> Output from executing the specified command\n"
	;
	fprintf(stderr, "%s", msg.c_str());
	exit(1);
}


text:
'use strict';

import Model from 'core/model';
import _ from 'underscore';

module.exports = Model.extend({
    initialize(activityEntities) {
        this.attributes.activities = this.createActivities(activityEntities);
    },

    createActivities(activityEntities) {
        let mergedActivities = [];

        for (let activityEntity of activityEntities) {
            let activity = activityEntity.getActivities();

            for (let data of activity) {
                mergedActivities.push(data);
            }
        }

        return (_.sortBy(mergedActivities, 'created_time'));
    }
});


text:
import Storex from '@worldbrain/storex'

import AbstractModel from './abstract-model'

const favIcon = Symbol('favIconURI')

export interface Props {
    hostname: string
    favIconURI: string
}

export default class FavIcon extends AbstractModel {
    public hostname: string
    public favIcon: Blob

    constructor(db: Storex, { hostname, favIconURI }: Props) {
        super(db)

        this.hostname = hostname
        this.favIconURI = favIconURI

        // Non-enumerable prop to hold the favIcon in-mem Blob link
        Object.defineProperty(this, favIcon, AbstractModel.DEF_NON_ENUM_PROP)
    }

    get data() {
        return {
            hostname: this.hostname,
            favIcon: this.favIcon,
        }
    }

    get favIconURI() {
        if (this.favIcon && !this[favIcon]) {
            return AbstractModel.getBlobURL(this.favIcon)
        }

        return this[favIcon]
    }

    set favIconURI(dataURI: string) {
        if (dataURI) {
            try {
                this.favIcon = AbstractModel.dataURLToBlob(dataURI)
                this[favIcon] = AbstractModel.getBlobURL(this.favIcon)
            } catch (err) {
                console.error(err)
            }
        }
    }

    public async delete() {
        return this.db
            .collection('favIcons')
            .deleteOneObject({ hostname: this.hostname })
    }

    public async save() {
        if (this.favIcon !== null) {
            const { object } = await this.db
                .collection('favIcons')
                .createObject(this.data)
            return object.hostname
        }
    }
}


text:
using System.Diagnostics;
using System.IO;
using Microsoft.Xna.Framework.Content.Pipeline;
using Microsoft.Xna.Framework.Content.Pipeline.Serialization.Compiler;
using MonoGame.Extended.TextureAtlases;

namespace MonoGame.Extended.Content.Pipeline.TextureAtlases
{
    [ContentTypeWriter]
    public class TexturePackerWriter : ContentTypeWriter<TexturePackerProcessorResult>
    {
        protected override void Write(ContentWriter writer, TexturePackerProcessorResult result)
        {
            var data = result.Data;
            var metadata = data.Metadata;

            var assetName = Path.GetFileNameWithoutExtension(metadata.Image);
            Debug.Assert(assetName != null, "assetName != null");

            writer.Write(assetName);
            writer.Write(data.Regions.Count);

            foreach (var region in data.Regions)
            {
                var regionName = Path.GetFileNameWithoutExtension(region.Filename);
                Debug.Assert(regionName != null, "regionName != null");

                writer.Write(regionName);
                writer.Write(region.Frame.X);
                writer.Write(region.Frame.Y);
                writer.Write(region.Frame.Width);
                writer.Write(region.Frame.Height);
            }
        }

        public override string GetRuntimeType(TargetPlatform targetPlatform)
        {
            return typeof(TextureAtlas).AssemblyQualifiedName;
        }

        public override string GetRuntimeReader(TargetPlatform targetPlatform)
        {
            return typeof(TextureAtlasReader).AssemblyQualifiedName;
        }
    }
}


text:
from functools import wraps

# THIRD PARTY
from django.http import HttpResponseForbidden
from google.appengine.api.users import is_current_user_admin

def is_cron(request):
    """ Is the given request generated by an App Engine cron job? """
    return request.META.get("HTTP_X_APPENGINE_CRON") or False

def is_task(request):
    """ Is the given request being ru by an App Engine cron job? """
    return request.META.get("HTTP_X_APPENGINE_QUEUENAME") or False

def gae_admin_cron_or_task_only(view_func):
    """ View decorator that requires the user to be an administrator of the App Engine app.
        Treats that anything being run in a cron or a task as being an admin user.
    """
    @wraps(view_func)
    def new_view(request, *args, **kwargs):
        if not (is_current_user_admin() or is_cron(request) or is_task(request)):
            return HttpResponseForbidden("Admin users only.")
        return view_func(request, *args, **kwargs)
    return new_view


text:
#include "q7filemanager.h"

#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QPushButton>
#include <QLineEdit>
#include <QPlainTextEdit>
#include <QTreeView>
#include <QAbstractItemModel>
#include <QStandardItemModel>
#include <QDesktopServices>
#include <QUrl>

#include <QDir>
#include <QFileIconProvider>

#include "Q7SortFilerProxyModel.h"

static QPlainTextEdit * gbl_logMsg;

void logMsg(const QString & text)
{
    gbl_logMsg->appendPlainText(text);
}

static QStandardItemModel *createEmptyModel(QObject *parent)
{
    QStandardItemModel *model = new QStandardItemModel(0, 7, parent);

    model->setHeaderData(0, Qt::Horizontal, QObject::tr("Name"));
    model->setHeaderData(1, Qt::Horizontal, QObject::tr("Size"));
    model->setHeaderData(2, Qt::Horizontal, QObject::tr("Modified"));
    model->setHeaderData(3, Qt::Horizontal, QObject::tr("Created"));
    model->setHeaderData(4, Qt::Horizontal, QObject::tr("Accessed"));
    model->setHeaderData(5, Qt::Horizontal, QObject::tr("Attributes"));
    model->setHeaderData(6, Qt::Horizontal, QObject::tr("Packed Size"));
    // model->setHeaderData(7, Qt::Horizontal, QObject::tr("Comment"));

    return model;
}

Q7FileManager::Q7FileManager(QWidget *parent)
    : QMainWindow(parent)
{
    this->setWindowTitle(tr("Q7zip"));

    QWidget * centralWidget = new QWidget;
    QVBoxLayout * layout = new QVBoxLayout(centralWidget);

    m_listView = new QTreeView();
    m_logMsg = new QPlainTextEdit;
    m_logMsg->setReadOnly(true);
    gbl_logMsg = m_logMsg;

    //////////////////////

    m_listView_proxyModel = new Q7SortFilerProxyModel(this);
    m_listView_proxyModel->setDynamicSortFilter(true);

    m_listView = new QTreeView;
    m_listView->setRootIsDecorated(false);
    m_listView->setAlternatingRowColors(true);
    m_listView->setModel(m_listView_proxyModel);
    m_listView->setSortingEnabled(m_listView_proxyModel);
    m_listView->sortByColumn(0, Qt::AscendingOrder);

    connect(m_listView,SIGNAL(doubleClicked(QModelIndex)) , this, SLOT(item_doubleClicked(QModelIndex)));

    layout->addWidget( buildLineEdit() );
    layout->addWidget(m_listView);
    layout->addWidget(m_logMsg);

    setCentralWidget(centralWidget);

    m_dirModel = createEmptyModel(this);
    this->setSourceModel( m_dirModel );

    resize(800,600);

    logMsg("line1");
    logMsg("Ok");
}

QWidget * Q7FileManager::buildLineEdit()
{
    QWidget * w = new QWidget;
    QHBoxLayout * layout = new QHBoxLayout(w);

    m_btnParent = new QPushButton(tr("Up"));
    connect(m_btnParent,SIGNAL(clicked()),this,SLOT(on_Parent()));

    m_pathEdit = new QLineEdit();

    layout->addWidget(m_btnParent);
    layout->addWidget(m_pathEdit);

    return w;
}

void Q7FileManager::on_Parent()
{
    QDir dir(m_dirPath);

    dir.cdUp();
    this->setDir(dir.absolutePath());
}

void Q7FileManager::item_doubleClicked(const QModelIndex & ind)
{
    // FIXME : how to have the column 0 ?

    QModelIndex ind2 = m_listView_proxyModel->mapToSource(ind);

    // QStandardItem * item = m_dirModel->itemFromIndex(ind2); // ->text();

    QStandardItem * item = m_dirModel->item(ind2.row(),0);

    if (item)
    {
        QString name = item->text(); // items.value(0).toString();
        QFileInfo fi( m_dirPath, name );
        if (fi.isDir())
        {
            logMsg(tr(" DIR  : %1").arg(name));
            this->setDir(fi.absoluteFilePath());
        }
        else
        {
            QUrl url("file://"+fi.absoluteFilePath(),QUrl::TolerantMode);

            bool bret = QDesktopServices::openUrl(url);
            logMsg(tr(" FILE : %1 => %2").arg(name).arg(bret));

        }

    }

}

void Q7FileManager::setDir(const QString & dirPath)
{
    m_dirPath = dirPath;
    m_pathEdit->setText(m_dirPath);

    // FIXME - clear
    m_dirModel = createEmptyModel(this);

    QDir dir(dirPath);
    dir.setFilter(QDir::AllEntries | QDir::Hidden | QDir::NoDotAndDotDot); // QDir::NoSymLinks
    // dir.setSorting(QDir::Size | QDir::Reversed);

    QFileInfoList list = dir.entryInfoList();
    for (int i = 0; i < list.size(); ++i) {
        QFileInfo fileInfo = list.at(i);

        m_dirModel->insertRow(0);
        /*
              QStyle * style = this->style();
        if (fileInfo.isDir())
        {
            QIcon icon = style->standardIcon ( QStyle::SP_DirIcon );
            m_dirModel->setItem(0, 0, new QStandardItem ( icon, fileInfo.fileName() ));
        }
        else
        {
            QIcon icon = style->standardIcon ( QStyle::SP_FileIcon );
            m_dirModel->setItem(0, 0, new QStandardItem ( icon, fileInfo.fileName() ));
        }
        */
        QStandardItem * item = new QStandardItem ( QFileIconProvider().icon(fileInfo) , fileInfo.fileName() );
        item->setEditable(false);
        m_dirModel->setItem(0, 0, item);

        m_dirModel->setData(m_dirModel->index(0, 1), fileInfo.size());
        m_dirModel->item(0,1)->setEditable(false);

        m_dirModel->setData(m_dirModel->index(0, 2), fileInfo.lastModified());
        m_dirModel->item(0,2)->setEditable(false);

        m_dirModel->setData(m_dirModel->index(0, 3), fileInfo.created());
        m_dirModel->item(0,3)->setEditable(false);

        m_dirModel->setData(m_dirModel->index(0, 4), fileInfo.lastRead());
        m_dirModel->item(0,4)->setEditable(false);

        if (fileInfo.isDir())  m_dirModel->setData(m_dirModel->index(0, 5), "drw-r-----");  // FIXME
        else                   m_dirModel->setData(m_dirModel->index(0, 5), "-rw-r-----");  // FIXME
        m_dirModel->item(0,5)->setEditable(false);

        m_dirModel->setData(m_dirModel->index(0, 6), fileInfo.size());  // FIXME
        m_dirModel->item(0,6)->setEditable(false);
    }

    // FIXME
    m_listView_proxyModel->setSourceModel(m_dirModel);
}

void Q7FileManager::setSourceModel(QAbstractItemModel *model)
{
    m_listView_proxyModel->setSourceModel(model);
}

Q7FileManager::~Q7FileManager()
{

}


text:
package com.intellij.debugger.streams.trace.impl.handler;

import com.intellij.debugger.streams.trace.impl.handler.type.GenericType;
import com.intellij.debugger.streams.wrapper.CallArgument;
import com.intellij.debugger.streams.wrapper.IntermediateStreamCall;
import com.intellij.debugger.streams.wrapper.StreamCallType;
import com.intellij.debugger.streams.wrapper.impl.CallArgumentImpl;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.CommonClassNames;
import org.jetbrains.annotations.NotNull;

import java.util.Collections;
import java.util.List;

/**
 * @author Vitaliy.Bibaev
 */
public class PeekCall implements IntermediateStreamCall {
  private final List<CallArgument> myLambda;
  private final GenericType myElementType;

  public PeekCall(@NotNull String lambda, @NotNull GenericType elementType) {
    myLambda = Collections.singletonList(new CallArgumentImpl(CommonClassNames.JAVA_LANG_OBJECT, lambda));
    myElementType = elementType;
  }

  @NotNull
  @Override
  public String getName() {
    return "peek";
  }

  @NotNull
  @Override
  public List<CallArgument> getArguments() {
    return myLambda;
  }

  @NotNull
  @Override
  public TextRange getTextRange() {
    return TextRange.EMPTY_RANGE;
  }

  @NotNull
  @Override
  public StreamCallType getType() {
    return StreamCallType.INTERMEDIATE;
  }

  @NotNull
  @Override
  public GenericType getTypeAfter() {
    return myElementType;
  }

  @NotNull
  @Override
  public GenericType getTypeBefore() {
    return myElementType;
  }
}


text:
package nl.dekkr.feedfrenzy.backend.extractor.action

import nl.dekkr.feedfrenzy.backend.model.Regex

class RegexAction extends BaseAction {

  def execute(vars: VariableMap, a: Regex): List[String] =
    getVariable(a.inputVariable, vars) map { input =>
      a.regex.r.findFirstMatchIn(input) match {
        case Some(found) => found.matched
        case None => ""
      }
    }

}


text:
using SharpDX.D3DCompiler;
using SharpDX.Direct3D11;
using SharpDX.Mathematics.Interop;

namespace PersistentPlanet.Graphics.DirectX11
{
    public class TexturePixelShader : IShader
    {
        private readonly string _filename;
        private readonly string _function;
        private readonly Texture2D _texture2d;

        private SharpDX.Direct3D11.PixelShader _pixelShader;
        private ShaderResourceView _texture;
        private SamplerState _samplerState;

        public TexturePixelShader(string filename, string function, Texture2D texture = null)
        {
            _filename = filename;
            _function = function;
            _texture2d = texture;
        }

        public void Initialise(D11InitialiseContext context)
        {
            using (var byteCode = ShaderBytecode.CompileFromFile(_filename, _function, "ps_4_0", ShaderFlags.Debug))
            {
                _pixelShader = new SharpDX.Direct3D11.PixelShader(context.Device, byteCode);
            }

            _samplerState = new SamplerState(context.Device, new SamplerStateDescription
            {
                Filter = Filter.ComparisonMinMagMipLinear,
                AddressU = TextureAddressMode.Wrap,
                AddressV = TextureAddressMode.Wrap,
                AddressW = TextureAddressMode.Wrap,
                MipLodBias = 0,
                MaximumAnisotropy = 1,
                ComparisonFunction = Comparison.Always,
                BorderColor = new RawColor4(0, 0, 0, 0),
                MinimumLod = 0,
                MaximumLod = float.MaxValue
            });

            if (_texture2d == null)
            {
                using (var bitmap = TextureLoader.LoadBitmap(new SharpDX.WIC.ImagingFactory2(), "sand.jpg"))
                using (var texture = TextureLoader.CreateTexture2DFromBitmap(context.Device, bitmap))
                {
                    _texture = new ShaderResourceView(context.Device, texture);
                }
            }
            else
            {
                _texture = new ShaderResourceView(context.Device, _texture2d);
            }
        }

        public void Dispose()
        {
            _samplerState?.Dispose();
            _pixelShader?.Dispose();
            _texture?.Dispose();
        }

        public void Apply(D11RenderContext renderContext)
        {
            renderContext.Context.PixelShader.Set(_pixelShader);
            renderContext.Context.PixelShader.SetShaderResource(0, _texture);
            renderContext.Context.PixelShader.SetSampler(0, _samplerState);
        }
    }
}


text:
<?php
defined( 'ABSPATH' ) or die( 'Cheatin’ uh?' );

if ( class_exists( 'BuddyPress' ) ) :
	/**
	 * Conflict with BuddyPress: don't apply LazyLoad on BuddyPress profil pages & group creation
	 *
	 * @since 2.8.15 Improve checks for user profile & disable for cover images
	 * @since 2.6.9
	 */
	if ( function_exists( 'bp_is_user_profile' ) ) :
		/**
		 * Prevent lazyload if on a BuddyPress profil page
		 *
		 * @param Bool $run_filter Do lazyload value.
		 * @return Bool False if on a BuddyPress profil page, initial value otherwise
		 */
		function rocket_deactivate_lazyload_on_buddypress_profil_pages( $run_filter ) {
			if ( bp_is_user_profile() ) {
				return false;
			}

			return $run_filter;
		}
		add_filter( 'do_rocket_lazyload', 'rocket_deactivate_lazyload_on_buddypress_profil_pages' );
		add_filter( 'do_rocket_lazyload_iframes', 'rocket_deactivate_lazyload_on_buddypress_profil_pages' );
	endif;

	if ( function_exists( 'bp_is_group_creation_step' ) && function_exists( 'bp_is_group_admin_screen' ) ) :
		/**
		 * Prevent lazyload if on a BuddyPress group creation page
		 *
		 * @param Bool $run_filter Do lazyload value.
		 * @return Bool False if on a BuddyPress profil page, initial value otherwise
		 */
		function rocket_deactivate_lazyload_on_buddypress_group_pages( $run_filter ) {
			if ( bp_is_group_creation_step( 'group-avatar' ) || bp_is_group_creation_step( 'group-cover-image' ) || bp_is_group_admin_screen( 'group-avatar' ) || bp_is_group_admin_screen( 'group-cover-image' ) ) {
				return false;
			}

			return $run_filter;
		}
		add_filter( 'do_rocket_lazyload', 'rocket_deactivate_lazyload_on_buddypress_group_pages' );
		add_filter( 'do_rocket_lazyload_iframes', 'rocket_deactivate_lazyload_on_buddypress_group_pages' );
	endif;
endif;


text:
/****************************************************************************/
/****************************************************************************/
// ===========================================================================
/****************************************************************************/

#include <asf.h>
#include "DataFlash.h"
#include "spi_master.h"
#include "conf_spi_master.h"

#include "SysLog.h"

/****************************************************************************/
// defines for all opcodes
#define BUFFER_1_WRITE 0x84			// buffer 1 write
#define BUFFER_2_WRITE 0x87			// buffer 2 write

#define BUFFER_1_READ 0xD4			// buffer 1 read
#define BUFFER_2_READ 0xD6			// buffer 2 read

// buffer 1 to main memory page program with built-in erase
#define B1PROGWITHERASE 0x83
// buffer 2 to main memory page program with built-in erase
#define B2PROGWITHERASE 0x86

// buffer 1 to main memory page program without built-in erase
#define B1PROGNOERASE 0x88
// buffer 2 to main memory page program without built-in erase
#define B2PROGNOERASE 0x89

// main memory page program through buffer 1
#define MM_PAGE_PROG_THROUGH_B1 0x82
// main memory page program through buffer 2
#define MM_PAGE_PROG_THROUGH_B2 0x85

// auto page rewrite through buffer 1
#define AUTO_PAGE_REWRITE_THROUGH_B1 0x58
// auto page rewrite through buffer 2
#define AUTO_PAGE_REWRITE_THROUGH_B2 0x59

// main memory page compare to buffer 1
#define MM_PAGE_TO_B1_COMP 0x60
// main memory page compare to buffer 2
#define MM_PAGE_TO_B2_COMP 0x61

// main memory page to buffer 1 transfer
#define MM_PAGE_TO_B1_XFER 0x53
// main memory page to buffer 2 transfer
#define MM_PAGE_TO_B2_XFER 0x55

// DataFlash status register for reading density, compare status,
// and ready/busy status
#define STATUS_REGISTER 0xD7	// was 0x57

#define MAIN_MEMORY_PAGE_READ 0xD2	// main memory page read
#define PAGE_ERASE 0x81				// erase a page
#define BLOCK_ERASE 0x50			// erase a block of pages

#define DEVICE_ID_READ		0x9F

/****************************************************************************/
/****************************************************************************/
#define MAX_PAGE_SIZE 528

struct spi_device df_spi = {
	/** Board specific select id */
	.id = SPI_DEVICE_EXAMPLE_ID
};

/****************************************************************************/
#define MASK(bit) (1<<(bit))	// bit number to bit mask
static uint32_t CS_Pin;
//static uint16_t NumChips;
static Spi *DF_Spi;
/****************************************************************************/
static void CS_On(void)
{
	spi_select_device(DF_Spi, &df_spi);
	PIOA->PIO_CODR = CS_Pin;
}

static void CS_Off(void)
{
	spi_deselect_device(DF_Spi, &df_spi);
	PIOA->PIO_SODR = CS_Pin;
}

static void CS_Init(void)
{
	PIOA->PIO_PER = CS_Pin;
	PIOA->PIO_OER = CS_Pin;
	PIOA->PIO_SODR = CS_Pin;
	CS_Off();
}

/****************************************************************************/
void DataFlash_Init(Spi *p_spi, uint32_t cs_pin)
{
  CS_Pin = cs_pin;
  DF_Spi = p_spi;
  CS_Init();
}

//*****************************************************************************
static int IsFlashReady (void)
{	// use page to determine which flash chip to test
	int status;

    CS_On();				// enable DataFlash
	spi_transfer(DF_Spi, STATUS_REGISTER);	// request status register
	status = spi_transfer(DF_Spi, 0xFF);			// write dummy value to start register shift
	CS_Off();				// disable DataFlash
	return (status & MASK(7));	// test the READY bit
}

//*****************************************************************************
uint8_t DFS_ReadChipID(void)
{
	uint8_t data;
	while ( !IsFlashReady() )
		;

	CS_On();
	spi_transfer(DF_Spi, DEVICE_ID_READ);
	spi_transfer(DF_Spi, 0);
	data = spi_transfer(DF_Spi, 0);
	CS_Off();
	return data;
}

//*****************************************************************************
static int TokenCheck(const DF_Token *tk, uint16_t page)
{
  return ( page >= tk->Size ) ? -1 : 0;
}

// ****************************************************************************
void DFS_ReadPageDirect (const DF_Token *tk, uint16_t page, uint16_t offset, uint16_t size, uint8_t *dest)
{	// Main Memory Page Read (does not use either buffer)
	// 24 address bits, 4 don't care bytes
	// address = 13 bits page, 10bits byte
	// 0ppp pppp pppp ppbb bbbb bbbb
	uint16_t i;

  if ( TokenCheck(tk, page) < 0 ) {
    return;
  }

	while ( !IsFlashReady() )
		;
  page += tk->FirstPage;

	CS_On();			// delay 250ns minimum till SCK (1.8T)
	spi_transfer(DF_Spi,MAIN_MEMORY_PAGE_READ);		// command byte
	spi_transfer(DF_Spi,page >> 6);
	spi_transfer(DF_Spi,(page << 2) | (offset >> 8));
	spi_transfer(DF_Spi,(uint8_t)offset);
	spi_transfer(DF_Spi,0);				// don't care bytes
	spi_transfer(DF_Spi,0);
	spi_transfer(DF_Spi,0);
	spi_transfer(DF_Spi,0);
	// ready to start reading
	for ( i=offset; i<(offset+size); i++ )
	{
		*dest++ = spi_transfer(DF_Spi,0);			// dummy write to generate clock pulses
	}
	// all done
	CS_Off();
}

// ****************************************************************************
void DFS_ReadFlashToBuffer (const DF_Token *tk, uint16_t page, DF_Buff whichbuf)
{	// do a Main Memory Page Read to Buffer
	// 24 address bits, 32 don't care bits
	// address = 1bits 0, 13bits page, 10bits 0
	// 0ppp pppp pppp pp00 0000 0000

  if ( TokenCheck(tk, page) < 0 ) {
    return;
  }

	while ( !IsFlashReady() )
		;

  page += tk->FirstPage;
	CS_On();			// delay 250ns minimum till SCK (1.8T)
	spi_transfer(DF_Spi,whichbuf==Buffer1?MM_PAGE_TO_B1_XFER:MM_PAGE_TO_B2_XFER);	// Main Memory Page Read to Buffer 1 or 2
	spi_transfer(DF_Spi,page>>6);
	spi_transfer(DF_Spi,(page<<2)+0);
	spi_transfer(DF_Spi,0);
	CS_Off();					// data transfered in 250us
}

// ****************************************************************************
void DFS_WriteBufferToFlash(const DF_Token *tk, uint16_t page, DF_Buff whichbuf)
{	// do a Buffer to Main Memory Page Write with auto-erase
	// 24 address bits, 32 don't care bits
	// address = 2bits 0, 13bits page, 10bits 0
	// 0ppp pppp pppp pp00 0000 0000

  if ( TokenCheck(tk, page) < 0 ) {
    return;
  }

	while ( !IsFlashReady() )
		;

  page += tk->FirstPage;
	CS_On();			// delay 250ns minimum till SCK (1.8T)
	spi_transfer(DF_Spi,whichbuf==Buffer1?B1PROGWITHERASE:B2PROGWITHERASE);	// Buffer to Main Memory Page write
	spi_transfer(DF_Spi,page>>6);
	spi_transfer(DF_Spi,(page<<2)+0);
	spi_transfer(DF_Spi,0);
	CS_Off();					// data written in 20ms (erase+write)
}

// ****************************************************************************
void DFS_BufferRead  (const DF_Token *tk, uint16_t page, uint16_t offset, uint16_t size, DF_Buff whichbuf, uint8_t *dest)
{	// start a Read from Buffer
	// 24 address bits, 8 don't care bits
	// address = 14 bits 0, 10bits byte
	// 0000 0000 0000 00bb bbbb bbbb
	uint16_t i;

  if ( TokenCheck(tk, page) < 0 ) {
    return;
  }

	while ( !IsFlashReady() )
		;
  page += tk->FirstPage;
	CS_On();			// delay 250ns minimum till SCK (1.8T)
	spi_transfer(DF_Spi,whichbuf==Buffer1?BUFFER_1_READ:BUFFER_2_READ);		// Read Buffer 1 or 2
	spi_transfer(DF_Spi,0);
	spi_transfer(DF_Spi,offset>>8);
	spi_transfer(DF_Spi,(uint8_t)offset);
	spi_transfer(DF_Spi,0);
	// ready to start reading
	for ( i=offset; i<(offset+size); i++ )
	{
		*dest++ = spi_transfer(DF_Spi,0);			// dummy write to generate clock pulses
	}
	// all done
	CS_Off();
}

// ****************************************************************************
void DFS_BufferWrite (const DF_Token *tk, uint16_t page, uint16_t offset, uint16_t size, DF_Buff whichbuf, const uint8_t *src)
{	// do a Write to Buffer
	// 24 address bits, 8 don't care bits
	// address = 14 bits 0, 10 bits byte
	// 0000 0000 0000 00bb bbbb bbbb
	uint16_t i;

  if ( TokenCheck(tk, page) < 0 ) {
    return;
  }

	while ( !IsFlashReady() )
		;

  page += tk->FirstPage;
	CS_On();			// delay 250ns minimum till SCK (1.8T)
	spi_transfer(DF_Spi,whichbuf==Buffer1?BUFFER_1_WRITE:BUFFER_2_WRITE);	// Write to Buffer 1 or 2
	spi_transfer(DF_Spi,0);
	spi_transfer(DF_Spi,offset>>8);
	spi_transfer(DF_Spi,(uint8_t)offset);
	// ready to start writing
	for ( i=offset; i<(offset+size); i++ )
	{
		spi_transfer(DF_Spi,*src++);		// write the byte
	}
	// all done
	CS_Off();
}

//*****************************************************************************
//*****************************************************************************