text:
<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');

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

 * Description:  returns HTML for client-side image map.
 * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
 * All Rights Reserved.
 * Contributor(s): ______________________________________..
 ********************************************************************************/

require_once("include/charts/Charts.php");
require_once("modules/Charts/code/Chart_pipeline_by_sales_stage.php");

global $app_list_strings, $current_language, $sugar_config, $currentModule, $action, $current_user, $theme, $timedate;
$user_dateFormat = $timedate->get_date_format();
$current_module_strings = return_module_language($current_language, 'Charts');

global $timedate;

if (isset($_REQUEST['mypbss_refresh'])) { $refresh = $_REQUEST['mypbss_refresh']; }
else { $refresh = false; }

//get the dates to display
$user_date_start = $current_user->getPreference('mypbss_date_start');

if (!empty($user_date_start) && !isset($_REQUEST['mypbss_date_start'])) {
	$date_start = $user_date_start;
	$GLOBALS['log']->debug("USER PREFERENCES['mypbss_date_start'] is:");
	$GLOBALS['log']->debug($user_date_start);
}
elseif (isset($_REQUEST['mypbss_date_start']) && $_REQUEST['mypbss_date_start'] != '') {
	$date_start = $_REQUEST['mypbss_date_start'];
	$current_user->setPreference('mypbss_date_start', $_REQUEST['mypbss_date_start']);
	$GLOBALS['log']->debug("_REQUEST['mypbss_date_start'] is:");
	$GLOBALS['log']->debug($_REQUEST['mypbss_date_start']);
	$GLOBALS['log']->debug("USER PREFERENCES['mypbss_date_start'] is:");
	$GLOBALS['log']->debug($current_user->getPreference('mypbss_date_start'));
}
else {
	$date_start = $timedate->nowDate();
}
$user_date_end = $current_user->getPreference('mypbss_date_end');

if (!empty($user_date_end) && !isset($_REQUEST['mypbss_date_end'])) {
	$date_end = $user_date_end;
	$GLOBALS['log']->debug("USER PREFERENCES['mypbss_date_end'] is:");
	$GLOBALS['log']->debug($user_date_end);
}
elseif (isset($_REQUEST['mypbss_date_end']) && $_REQUEST['mypbss_date_end'] != '') {
	$date_end = $_REQUEST['mypbss_date_end'];
	$current_user->setPreference('mypbss_date_end', $_REQUEST['mypbss_date_end']);
	$GLOBALS['log']->debug("_REQUEST['mypbss_date_end'] is:");
	$GLOBALS['log']->debug($_REQUEST['mypbss_date_end']);
	$GLOBALS['log']->debug("USER PREFERENCES['mypbss_date_end'] is:");
	$GLOBALS['log']->debug( $current_user->getPreference('mypbss_date_end'));
}
else {
	$date_end = $timedate->asUserDate($timedate->fromString("2010-01-01"));
	$GLOBALS['log']->debug("USER PREFERENCES['mypbss_date_end'] not found. Using: ".$date_end);
}

// cn: format date_start|end to user's preferred
$dateStartDisplay = strftime($timedate->get_user_date_format(), strtotime($date_start));
$dateEndDisplay  	= strftime($timedate->get_user_date_format(), strtotime($date_end));
$seps				= array("-", "/");
$dates				= array($date_start, $date_end);
$dateFileNameSafe	= str_replace($seps, "_", $dates);
$dateXml[0]			= $timedate->swap_formats($date_start, $user_dateFormat, $timedate->dbDayFormat);
$dateXml[1]			= $timedate->swap_formats($date_end, $user_dateFormat, $timedate->dbDayFormat);

$tempx = array();
$datax = array();
$selected_datax = array();
//get list of sales stage keys to display
$user_sales_stage = $current_user->getPreference('mypbss_sales_stages');
if (!empty($user_sales_stage) && count($user_sales_stage) > 0 && !isset($_REQUEST['mypbss_sales_stages'])) {
	$tempx = $user_sales_stage;
	$GLOBALS['log']->debug("USER PREFERENCES['mypbss_sales_stages'] is:");
	$GLOBALS['log']->debug($user_sales_stage);
}
elseif (isset($_REQUEST['mypbss_sales_stages']) && count($_REQUEST['mypbss_sales_stages']) > 0) {
	$tempx = $_REQUEST['mypbss_sales_stages'];
	$current_user->setPreference('mypbss_sales_stages', $_REQUEST['mypbss_sales_stages']);
	$GLOBALS['log']->debug("_REQUEST['mypbss_sales_stages'] is:");
	$GLOBALS['log']->debug($_REQUEST['mypbss_sales_stages']);
	$GLOBALS['log']->debug("USER PREFRENCES['mypbss_sales_stages'] is:");
	$GLOBALS['log']->debug($current_user->getPreference('mypbss_sales_stages'));
}

//set $datax using selected sales stage keys
if (count($tempx) > 0) {
	foreach ($tempx as $key) {
		$datax[$key] = $app_list_strings['sales_stage_dom'][$key];
		array_push($selected_datax, $key);
	}
}
else {
	$datax = $app_list_strings['sales_stage_dom'];
	$selected_datax = array_keys($app_list_strings['sales_stage_dom']);
}
$GLOBALS['log']->debug("datax is:");
$GLOBALS['log']->debug($datax);

$ids = array($current_user->id);
//create unique prefix based on selected users for image files
$id_hash = '1';
if (isset($ids)) {
	sort($ids);
	$id_hash = crc32(implode('',$ids));
	if($id_hash < 0)
	{
        $id_hash = $id_hash * -1;
	}
}
$GLOBALS['log']->debug("ids is:");
$GLOBALS['log']->debug($ids);
$id_md5 = substr(md5($current_user->id),0,9);
$seps				= array("-", "/");
$dates				= array($dateStartDisplay, $dateEndDisplay);
$dateFileNameSafe	= str_replace($seps, "_", $dates);
$cache_file_name = sugar_cached("xml/").$current_user->getUserPrivGuid()."_".$theme."_my_pipeline_".$dateFileNameSafe[0]."_".$dateFileNameSafe[1].".xml";

$GLOBALS['log']->debug("cache file name is: $cache_file_name");

$tools='
'.SugarThemeRegistry::current()->getImage('refresh','border="0" align="absmiddle"',null,null,'.gif',$mod_strings['LBL_REFRESH']).' '.$current_module_strings['LBL_REFRESH'].'  '.SugarThemeRegistry::current()->getImage('edit','border="0" align="absmiddle"',null,null,'.gif',$mod_strings['LBL_EDIT']).' '. $current_module_strings['LBL_EDIT'].'
';

?>
	<?php echo get_form_header($mod_strings['LBL_PIPELINE_FORM_TITLE'], $tools , false);?>

<?php
	global $timedate;
	$cal_lang = "en";
	$cal_dateformat = $timedate->get_cal_date_format();
?>

<form name='my_pipeline' action="index.php" method="post" >
<input type="hidden" name="module" value="<?php echo $currentModule;?>">
<input type="hidden" name="action" value="<?php echo $action;?>">
<input type="hidden" name="mypbss_refresh" value="true">

	<?php echo $current_module_strings['LBL_DATE_START']?>
<?php echo $timedate->get_user_date_format();?>
	<input onblur="parseDate(this, '<?php echo $cal_dateformat ?>');" class="text" name="mypbss_date_start" size='12' maxlength='10' id='date_start' value='<?php echo $date_start; ?>'> <?php echo SugarThemeRegistry::current()->getImage('jscalendar', 'id="date_start_trigger" align="absmiddle"', null, null, ".gif", $app_strings['LBL_ENTER_DATE']); ?>

	<?php echo $current_module_strings['LBL_DATE_END'];?>
<?php echo $timedate->get_user_date_format();?>
	<input onblur="parseDate(this, '<?php echo $cal_dateformat ?>');" class="text" name="mypbss_date_end" size='12' maxlength='10' id='date_end' value='<?php echo $date_end; ?>'>  <?php echo SugarThemeRegistry::current()->getImage('jscalendar', 'id="date_end_trigger" align="absmiddle"', null, null, ".gif", $app_strings['LBL_ENTER_DATE']); ?>

	<?php echo $current_module_strings['LBL_SALES_STAGES'];?>
	<select name="mypbss_sales_stages[]" multiple size='3'><?php echo get_select_options_with_id($app_list_strings['sales_stage_dom'],$selected_datax); ?></select>

	<input class="button" onclick="return verify_chart_data(my_pipeline);" type="submit" title="<?php echo $app_strings['LBL_SELECT_BUTTON_TITLE']; ?>" value="<?php echo $app_strings['LBL_SELECT_BUTTON_LABEL']?>" /><input class="button" onClick="javascript: toggleDisplay('my_pipeline_edit');" type="button" title="<?php echo $app_strings['LBL_CANCEL_BUTTON_TITLE']; ?>" accessKey="<?php echo $app_strings['LBL_CANCEL_BUTTON_KEY'];?>" value="<?php echo $app_strings['LBL_CANCEL_BUTTON_LABEL']?>"/>

</form>

<?php

echo "
".gen_xml_pipeline_by_sales_stage($datax, $dateXml[0], $dateXml[1], $ids, $cache_file_name, $refresh,'hBarS',$current_module_strings)."
";
echo "
".$current_module_strings['LBL_PIPELINE_FORM_TITLE_DESC']."
";

	if (file_exists($cache_file_name)) {
		$file_date = $timedate->asUser($timedate->fromTimestamp(filemtime($cache_file_name)));
	}
	else {
		$file_date = '';
	}

?>

<?php  echo $current_module_strings['LBL_CREATED_ON'].' '.$file_date; ?>

<?php
echo get_validate_chart_js();

	/**
	* Creates opportunity pipeline image as a HORIZONTAL accumlated BAR GRAPH for multiple users.
	* param $datax- the sales stage data to display in the x-axis
	* Portions created by SugarCRM are Copyright (C) SugarCRM, Inc..
	* All Rights Reserved..
	* Contributor(s): ______________________________________..
	*/
	function gen_xml_pipeline_by_sales_stage($datax=array('foo','bar'), $date_start='2071-10-15', $date_end='2071-10-15', $user_id=array('1'), $cache_file_name='a_file', $refresh=false,$chart_size='hBarF',$current_module_strings) {
		global $app_strings, $charset, $lang, $barChartColors, $current_user;

		$kDelim = $current_user->getPreference('num_grp_sep');
		global $timedate;

		if (!file_exists($cache_file_name) || $refresh == true) {

			$GLOBALS['log']->debug("starting pipeline chart");
			$GLOBALS['log']->debug("datax is:");
			$GLOBALS['log']->debug($datax);
			$GLOBALS['log']->debug("user_id is: ");
			$GLOBALS['log']->debug($user_id);
			$GLOBALS['log']->debug("cache_file_name is: $cache_file_name");
			$opp = new Opportunity;
			$where="";
			//build the where clause for the query that matches $user
			$count = count($user_id);
			$id = array();
			$user_list = get_user_array(false);
			foreach ($user_id as $key) {
				$new_ids[$key] = $user_list[$key];
			}
			if ($count>0) {
				foreach ($new_ids as $the_id=>$the_name) {
					$id[] = "'".$the_id."'";
				}
				$ids = join(",",$id);
				$where .= "opportunities.assigned_user_id IN ($ids) ";

			}
			//build the where clause for the query that matches $datax
			$count = count($datax);
			$dataxArr = array();
			if ($count>0) {

				foreach ($datax as $key=>$value) {
					$dataxArr[] = "'".$key."'";
				}
				$dataxArr = join(",",$dataxArr);
				$where .= "AND opportunities.sales_stage IN	($dataxArr) ";
			}

			//build the where clause for the query that matches $date_start and $date_end
			$where .= "	AND opportunities.date_closed >= ". db_convert("'".$date_start."'",'date'). "
						AND opportunities.date_closed <= ".db_convert("'".$date_end."'",'date') ;
			$where .= "	AND opportunities.assigned_user_id = users.id  AND opportunities.deleted=0 ";

			//Now do the db queries
			//query for opportunity data that matches $datax and $user
			$query = "	SELECT opportunities.sales_stage,
							users.user_name,
							opportunities.assigned_user_id,
							count( * ) AS opp_count,
							sum(amount_usdollar/1000) AS total
						FROM users,opportunities  ";
			$query .= "WHERE " .$where;
			$query .= " GROUP BY opportunities.sales_stage,users.user_name,opportunities.assigned_user_id";

			$result = $opp->db->query($query, true);
			//build pipeline by sales stage data
			$total = 0;
			$div = 1;
			global $sugar_config;
			$symbol = $sugar_config['default_currency_symbol'];
			global $current_user;
			if($current_user->getPreference('currency') ){

				$currency = new Currency();
				$currency->retrieve($current_user->getPreference('currency'));
				$div = $currency->conversion_rate;
				$symbol = $currency->symbol;
			}
			// cn: adding user-pref date handling
			$dateStartDisplay = $timedate->asUserDate($timedate->fromString($date_start));
			$dateEndDisplay = $timedate->asUserDate($timedate->fromString($date_end));

			$fileContents = '     <yData defaultAltText="'.$current_module_strings['LBL_ROLLOVER_DETAILS'].'">'."\n";
			$stageArr = array();
			$usernameArr = array();
			$rowTotalArr = array();
			$rowTotalArr[] = 0;
			while($row = $opp->db->fetchByAssoc($result, false))
			{
				if($row['total']*$div<=100){
					$sum = round($row['total']*$div, 2);
				} else {
					$sum = round($row['total']*$div);
				}
				if(!isset($stageArr[$row['sales_stage']]['row_total'])) {$stageArr[$row['sales_stage']]['row_total']=0;}
				$stageArr[$row['sales_stage']][$row['assigned_user_id']]['opp_count'] = $row['opp_count'];
				$stageArr[$row['sales_stage']][$row['assigned_user_id']]['total'] = $sum;
				$stageArr[$row['sales_stage']]['people'][$row['assigned_user_id']] = $row['user_name'];
				$stageArr[$row['sales_stage']]['row_total'] += $sum;

				$usernameArr[$row['assigned_user_id']] = $row['user_name'];
				$total += $sum;
			}
			foreach ($datax as $key=>$translation) {
				if(isset($stageArr[$key]['row_total'])){$rowTotalArr[]=$stageArr[$key]['row_total'];}
				if(isset($stageArr[$key]['row_total']) && $stageArr[$key]['row_total']>100) {
					$stageArr[$key]['row_total'] = round($stageArr[$key]['row_total']);
				}
				$fileContents .= '     <dataRow title="'.$translation.'" endLabel="';
				if(isset($stageArr[$key]['row_total'])){$fileContents .= $stageArr[$key]['row_total'];}
				$fileContents .= '">'."\n";
				if(isset($stageArr[$key]['people'])){
					asort($stageArr[$key]['people']);
					reset($stageArr[$key]['people']);
					foreach ($stageArr[$key]['people'] as $nameKey=>$nameValue) {
						$fileContents .= '          <bar id="'.$nameKey.'" totalSize="'.$stageArr[$key][$nameKey]['total'].'" altText="'.$nameValue.': '.$stageArr[$key][$nameKey]['opp_count'].' '.$current_module_strings['LBL_OPPS_WORTH'].' '.currency_format_number($stageArr[$key][$nameKey]['total'], array('currency_symbol'=>true)).$current_module_strings['LBL_OPP_THOUSANDS'].' '.$current_module_strings['LBL_OPPS_IN_STAGE'].' '.$translation.'" url="index.php?module=Opportunities&action=index&assigned_user_id[]='.$nameKey.'&sales_stage='.urlencode($key).'&date_start='.$date_start.'&date_closed='.$date_end.'&query=true&searchFormTab=advanced_search"/>'."\n";
					}
				}
				$fileContents .= '     </dataRow>'."\n";
			}
			$fileContents .= '     </yData>'."\n";
			$max = get_max($rowTotalArr);
			if($chart_size=='hBarF'){
				$length = "10";
			}else{
				$length = "4";
			}
			$fileContents .= '     <xData min="0" max="'.$max.'" length="'.$length.'" kDelim="'.$kDelim.'" prefix="'.$symbol.'" suffix=""/>'."\n";
			$fileContents .= '     <colorLegend status="on">'."\n";
			$i=0;
			asort($new_ids);
			foreach ($new_ids as $key=>$value) {
			$color = generate_graphcolor($key,$i);
			$fileContents .= '          <mapping id="'.$key.'" name="'.$value.'" color="'.$color.'"/>'."\n";
			$i++;
			}
			$fileContents .= '     </colorLegend>'."\n";
			$fileContents .= '     <graphInfo>'."\n";
			$fileContents .= '          <![CDATA['.$current_module_strings['LBL_DATE_RANGE'].' '.$dateStartDisplay.' '.$current_module_strings['LBL_DATE_RANGE_TO'].' '.$dateEndDisplay.'
'.$current_module_strings['LBL_OPP_SIZE'].' '.$symbol.'1'.$current_module_strings['LBL_OPP_THOUSANDS'].']]>'."\n";
			$fileContents .= '     </graphInfo>'."\n";
			$fileContents .= '     <chartColors ';
			foreach ($barChartColors as $key => $value) {
				$fileContents .= ' '.$key.'='.'"'.$value.'" ';
			}
			$fileContents .= ' />'."\n";
			$fileContents .= '</graphData>'."\n";
			$total = $total;
			$title = '<graphData title="'.$current_module_strings['LBL_TOTAL_PIPELINE'].currency_format_number($total, array('currency_symbol' => true)).$app_strings['LBL_THOUSANDS_SYMBOL'].'">'."\n";
			$fileContents = $title.$fileContents;

			save_xml_file($cache_file_name, $fileContents);
		}

		if($chart_size=='hBarF'){
			$width = "800";
			$height = "400";
		} else {
			$width = "350";
			$height = "400";
		}
		$return = create_chart($chart_size,$cache_file_name,$width,$height);
		return $return;
	}

	function constructQuery(){
		global $current_user;
		global $timedate;

		//get the dates to display
		$user_date_start = $current_user->getPreference('mypbss_date_start');

		if (!empty($user_date_start) && !isset($_REQUEST['mypbss_date_start'])) {
			$date_start = $user_date_start;
			$GLOBALS['log']->debug("USER PREFERENCES['mypbss_date_start'] is:");
			$GLOBALS['log']->debug($user_date_start);
		}
		elseif (isset($_REQUEST['mypbss_date_start']) && $_REQUEST['mypbss_date_start'] != '') {
			$date_start = $_REQUEST['mypbss_date_start'];
			$current_user->setPreference('mypbss_date_start', $_REQUEST['mypbss_date_start']);
			$GLOBALS['log']->debug("_REQUEST['mypbss_date_start'] is:");
			$GLOBALS['log']->debug($_REQUEST['mypbss_date_start']);
			$GLOBALS['log']->debug("USER PREFERENCES['mypbss_date_start'] is:");
			$GLOBALS['log']->debug($current_user->getPreference('mypbss_date_start'));
		}
		else {
			$date_start = $timedate->nowDate();
		}
		$user_date_end = $current_user->getPreference('mypbss_date_end');

		if (!empty($user_date_end) && !isset($_REQUEST['mypbss_date_end'])) {
			$date_end = $user_date_end;
			$GLOBALS['log']->debug("USER PREFERENCES['mypbss_date_end'] is:");
			$GLOBALS['log']->debug($user_date_end);
		}
		elseif (isset($_REQUEST['mypbss_date_end']) && $_REQUEST['mypbss_date_end'] != '') {
			$date_end = $_REQUEST['mypbss_date_end'];
			$current_user->setPreference('mypbss_date_end', $_REQUEST['mypbss_date_end']);
			$GLOBALS['log']->debug("_REQUEST['mypbss_date_end'] is:");
			$GLOBALS['log']->debug($_REQUEST['mypbss_date_end']);
			$GLOBALS['log']->debug("USER PREFERENCES['mypbss_date_end'] is:");
			$GLOBALS['log']->debug( $current_user->getPreference('mypbss_date_end'));
		}
		else {
			$date_end = $timedate->asUserDate($timedate->fromString("2010-01-01"));
			$GLOBALS['log']->debug("USER PREFERENCES['mypbss_date_end'] not found. Using: ".$date_end);
		}

		$user_id = array($current_user->id);

		$opp = new Opportunity;
		$where="";
		//build the where clause for the query that matches $user
		$count = count($user_id);
		$id = array();
		$user_list = get_user_array(false);
		foreach ($user_id as $key) {
			$new_ids[$key] = $user_list[$key];
		}
		if ($count>0) {
			foreach ($new_ids as $the_id=>$the_name) {
				$id[] = "'".$the_id."'";
			}
			$ids = join(",",$id);
			$where .= "opportunities.assigned_user_id IN ($ids) ";
		}
		//build the where clause for the query that matches $datax
		$count = count($datax);
		$dataxArr = array();
		if ($count>0) {
			foreach ($datax as $key=>$value) {
				$dataxArr[] = "'".$key."'";
			}
			$dataxArr = join(",",$dataxArr);
			$where .= "AND opportunities.sales_stage IN	($dataxArr) ";
		}

		//build the where clause for the query that matches $date_start and $date_end
		$where .= "	AND opportunities.date_closed >= ". db_convert("'".$date_start."'",'date'). "
					AND opportunities.date_closed <= ".db_convert("'".$date_end."'",'date') ;
		$where .= "	AND opportunities.assigned_user_id = users.id  AND opportunities.deleted=0 ";

		//Now do the db queries
		//query for opportunity data that matches $datax and $user
		$query = "	SELECT opportunities.sales_stage,
						users.user_name,
						opportunities.assigned_user_id,
						count( * ) AS opp_count,
						sum(amount_usdollar/1000) AS total
					FROM users,opportunities  ";
		$query .= "WHERE " .$where;
		$query .= " GROUP BY opportunities.sales_stage,users.user_name,opportunities.assigned_user_id";

		return $query;

	}

	function constructGroupBy(){
		return array('sales_stage');
	}

?>


text:
{-# LANGUAGE AllowAmbiguousTypes, DataKinds, DefaultSignatures,
             FlexibleContexts, MultiParamTypeClasses, TypeFamilies,
             TypeOperators #-}

{- |
   Module      : Data.Keyless
   Description : Class of lookup tables with generated keys.
   Copyright   : (c) Ivan Lazar Miljenovic
   License     : 3-Clause BSD-style
   Maintainer  : Ivan.Miljenovic@gmail.com

This module defines a class for when you want to store data in a
lookup table/dictionary but the type/value of the key isn't important.

-}
module Data.Keyless where

import Prelude hiding (lookup, map)

-- -----------------------------------------------------------------------------

-- | The keys of the values in the 'Keyless' tables.  Note that all
--   keys will be @>= 0@ and no key will be repeated (even if the
--   value corresponding to the maximal key is deleted and then a new
--   value is added, a new higher key will be returned).
type Key = Int

-- | The minimum key used.
initKey :: Key
initKey = 0

class Keyless c where

  -- | The type of values stored in this keyless table.
  type Elem c :: *

  -- | Additional arguments used when building a keyless table.
  --   Defaults to @'[]@.
  type BuildArgs c :: [*]
  type BuildArgs c = '[]

  -- | A blank lookup table.
  empty :: BuildArguments c c

  -- | Insert the provided value into the table
  insert :: Elem c -> c -> (Key, c)

  -- | Add multiple values into the table.
  insertBulk :: [Elem c] -> c -> ([Key], c)

  -- | Remove the specified entry from the table.  Won't do anything
  --   if the key is not in the table.
  delete :: Key -> c -> c

  -- | Remove multiple entries from the table.
  deleteBulk :: [Key] -> c -> c

  -- | Return the value associated with the specified key if it is in
  --   the table.
  lookup :: Key -> c -> Maybe (Elem c)

  -- | As with 'lookup', but assumes the key is in the table.
  unsafeLookup :: Key -> c -> Elem c

  -- | Is the following entry in the table?
  hasEntry :: Key -> c -> Bool

  -- | Apply a function on the value associated with the specified key.
  adjust :: (Elem c -> Elem c) -> Key -> c -> c

  -- | How many values are currently stored.
  size :: c -> Int
  size = length . keys

  -- | The smallest key being used; 'Nothing' indicates 'isNull'.
  minKey :: c -> Maybe Key

  -- | The largest key being used; 'Nothing' indicates 'isNull'.  Note
  --   that the next key will /not/ necessarily be @(+1)@ of this.
  maxKey :: c -> Maybe Key

  -- | Are there any values being stored?
  isNull :: c -> Bool

  -- | Return all keys in the table.
  keys :: c -> [Key]

  -- | Return all values in the table.
  values :: c -> [Elem c]

  -- | Return all @(key,value)@ pairs in the table.
  assocs :: c -> [(Key, Elem c)]

  -- | Create a table from a list of specified values.  The value at
  --   @xs !! k@ will be associated with the key @k@ in @fromList xs@.
  fromList :: BuildArguments c ([Elem c] -> c)

  -- | Create a table from the specified @(key,value)@ pairs (this is
  --   the inverse of @assocs@).
  --
  --   The keys are /not/ assumed to be in any particular order
  --   (i.e. they will probably be sorted first, which will thus
  --   affect performance).
  unsafeFromListWithKeys :: BuildArguments c ([(Key, Elem c)] -> c)

  -- | Merge the two tables together by \"appending\" the second table
  --   to the first.  Also returned is the translation function
  --   between keys from the second table to the first.
  merge :: c -> c -> (Key -> Key, c)

  -- | Given a non-empty list of tables, merge them all together in
  --   order and provide the translation function for each (the first
  --   function will be @'id'@).
  --
  --   An empty list will return the 'empty' table.
  mergeAll :: [c] -> ([MergeTranslation Key], c)

  -- | Remove any keys present in the second table from the first.
  difference :: c -> c -> c

-- | 'Keyless' tables that can be deconstructed into the container (of
--   kind @* -> *@) and the value being stored.
--
--   The @a@ parameter remains in case of instances with constraints
--   on the values used.
class (Keyless (c a), Elem (c a) ~ a) => FKeyless c a where

  map :: (FKeyless c b) => (a -> b) -> c a -> c b
  default map :: (Functor c) => (a -> b) -> c a -> c b
  map = fmap

  -- | Apply a mapping function over the values in the table whilst
  --   also considering the actual keys.
  mapWithKey :: (FKeyless c b) => (Key -> a -> b) -> c a -> c b

-- Need equivalent of M.unions for non-overlapping tables?

-- Traversal and face-finding code currently takes advantage of using
-- Map to do difference; better way of doing it?

-- | A flipped, infix alias for 'unsafeLookup'.
(!) :: (Keyless c) => c -> Key -> Elem c
c ! k = unsafeLookup k c

-- | A flipped, infix alias for 'lookup'.
(!?) :: (Keyless c) => c -> Key -> Maybe (Elem c)
c !? a = lookup a c

-- | When merging multiple 'Keyless' tables together, to be able to
--   translate values from each original table to the new values and
--   positions several pieces of information are needed:
--
--   * The keys in the new table that corresponds to the original;
--     this is the keys bounded by 'newBounds' inclusive.  Bounds of
--     'Nothing' denote that the original table was 'null'.
--
--   * The /partial/ function in 'oldToNew' translates keys from the
--     old table to keys in the new table.
data MergeTranslation k = MT { -- | The portion of the new table from
                               --   the applicable old table.
                               newBounds :: !(Maybe (k,k))
                               -- | The translation function for keys
                               --   from the original table to the new
                               --   one.
                             , oldToNew  :: !(k -> k)
                             }

-- | Expand a list of extra arguments out as function parameters.
--
--   For example, @ApplyOperands '[Int, Char] Bool ~ Int -> Char -> Bool@.
type family ApplyOperands (os :: [*]) r where
  ApplyOperands '[] r = r
  ApplyOperands (o ': os) r = o -> ApplyOperands os r

-- | The arguments needed to create a 'Keyless' value @c@ with a
--   result type of @r@.
type BuildArguments c r = ApplyOperands (BuildArgs c) r

redpajama_set_name: RedPajamaGithub


text:
package org.apache.http.HC4.entity;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.http.HC4.annotation.NotThreadSafe;
import org.apache.http.HC4.util.Args;
import org.apache.http.HC4.entity.AbstractHttpEntity;

/**
 * A streamed, non-repeatable entity that obtains its content from
 * an {@link InputStream}.
 *
 * @since 4.0
 */
@NotThreadSafe
public class InputStreamEntity extends AbstractHttpEntity {

    private final InputStream content;
    private final long length;

    /**
     * Creates an entity with an unknown length.
     * Equivalent to {@code new InputStreamEntity(instream, -1)}.
     *
     * @param instream input stream
     * @throws IllegalArgumentException if {@code instream} is {@code null}
     * @since 4.3
     */
    public InputStreamEntity(final InputStream instream) {
        this(instream, -1);
    }

    /**
     * Creates an entity with a specified content length.
     *
     * @param instream input stream
     * @param length of the input stream, {@code -1} if unknown
     * @throws IllegalArgumentException if {@code instream} is {@code null}
     */
    public InputStreamEntity(final InputStream instream, final long length) {
        this(instream, length, null);
    }

    /**
     * Creates an entity with a content type and unknown length.
     * Equivalent to {@code new InputStreamEntity(instream, -1, contentType)}.
     *
     * @param instream input stream
     * @param contentType content type
     * @throws IllegalArgumentException if {@code instream} is {@code null}
     * @since 4.3
     */
    public InputStreamEntity(final InputStream instream, final ContentType contentType) {
        this(instream, -1, contentType);
    }

    /**
     * @param instream input stream
     * @param length of the input stream, {@code -1} if unknown
     * @param contentType for specifying the {@code Content-Type} header, may be {@code null}
     * @throws IllegalArgumentException if {@code instream} is {@code null}
     * @since 4.2
     */
    public InputStreamEntity(final InputStream instream, final long length, final ContentType contentType) {
        super();
        this.content = Args.notNull(instream, "Source input stream");
        this.length = length;
        if (contentType != null) {
            setContentType(contentType.toString());
        }
    }

    @Override
    public boolean isRepeatable() {
        return false;
    }

    /**
     * @return the content length or {@code -1} if unknown
     */
    @Override
    public long getContentLength() {
        return this.length;
    }

    @Override
    public InputStream getContent() throws IOException {
        return this.content;
    }

    /**
     * Writes bytes from the {@code InputStream} this entity was constructed
     * with to an {@code OutputStream}.  The content length
     * determines how many bytes are written.  If the length is unknown ({@code -1}), the
     * stream will be completely consumed (to the end of the stream).
     *
     */
    @Override
    public void writeTo(final OutputStream outstream) throws IOException {
        Args.notNull(outstream, "Output stream");
        final InputStream instream = this.content;
        try {
            final byte[] buffer = new byte[OUTPUT_BUFFER_SIZE];
            int l;
            if (this.length < 0) {
                // consume until EOF
                while ((l = instream.read(buffer)) != -1) {
                    outstream.write(buffer, 0, l);
                }
            } else {
                // consume no more than length
                long remaining = this.length;
                while (remaining > 0) {
                    l = instream.read(buffer, 0, (int)Math.min(OUTPUT_BUFFER_SIZE, remaining));
                    if (l == -1) {
                        break;
                    }
                    outstream.write(buffer, 0, l);
                    remaining -= l;
                }
            }
        } finally {
            instream.close();
        }
    }

    @Override
    public boolean isStreaming() {
        return true;
    }

}


text:
import hashlib
from xml.dom import NamespaceErr

from defusedxml import ElementTree as ET

from dojo.models import Endpoint, Finding

__author__ = 'dr3dd589'

class SslscanParser(object):

    def get_scan_types(self):
        return ["Sslscan"]

    def get_label_for_scan_types(self, scan_type):
        return scan_type  # no custom label for now

    def get_description_for_scan_types(self, scan_type):
        return "Import XML output of sslscan report."

    def get_findings(self, file, test):
        tree = ET.parse(file)
        # get root of tree.
        root = tree.getroot()
        if 'document' not in root.tag:
            raise NamespaceErr("This doesn't seem to be a valid sslscan xml file.")
        dupes = dict()
        for ssltest in root:
            for target in ssltest:
                title = ""
                severity = ""
                description = ""
                severity = "Info"
                host = ssltest.attrib['host']
                port = int(ssltest.attrib['port'])
                if target.tag == "heartbleed" and target.attrib['vulnerable'] == '1':
                    title = "heartbleed" + " | " + target.attrib['sslversion']
                    description = "**heartbleed** :" + "\n\n" + \
                                "**sslversion** : " + target.attrib['sslversion'] + "\n"
                if target.tag == "cipher" and target.attrib['strength'] not in ['acceptable', 'strong']:
                    title = "cipher" + " | " + target.attrib['sslversion']
                    description = "**Cipher** : " + target.attrib['cipher'] + "\n\n" + \
                                "**Status** : " + target.attrib['status'] + "\n\n" + \
                                "**strength** : " + target.attrib['strength'] + "\n\n" + \
                                "**sslversion** : " + target.attrib['sslversion'] + "\n"

                if title and description is not None:
                    dupe_key = hashlib.sha256(str(description + title).encode('utf-8')).hexdigest()
                    if dupe_key in dupes:
                        finding = dupes[dupe_key]
                        if finding.references:
                            finding.references = finding.references
                        dupes[dupe_key] = finding
                    else:
                        dupes[dupe_key] = True

                        finding = Finding(
                            title=title,
                            test=test,
                            description=description,
                            severity=severity,
                            dynamic_finding=True,)
                        finding.unsaved_endpoints = list()
                        dupes[dupe_key] = finding

                        if host:
                            if '://' in host:
                                endpoint = Endpoint.from_uri(host)
                            else:
                                endpoint = Endpoint(
                                    host=host,
                                    port=port)
                            finding.unsaved_endpoints.append(endpoint)
        return dupes.values()


text:
BaseConverter+
=============

This is a redesign of my first Android app, [BaseConverter](https://github.com/codemonkey800/BaseConverter). I made
BaseConverter in my senior year. Now that Lollipop and Material Design is a thing, I wanted to redesign the app to test out Material Design.

Building
========
Building is simple. Just run
```
    gradle build
```
or import the project into Android Studio as a Gradle project, Gradle Sync, and build.

Excelsior!
==========
![](http://goo.gl/S6qY2O)


text:
import { Button } from "../../button/button";
import ButtonView from "../../button/buttonview";
import IconView from "../../icon/iconview";
import { DropdownButton } from "./dropdownbutton";

export default class DropdownButtonView extends ButtonView implements DropdownButton, Button {
    readonly arrowView: IconView;
}


text:
package org.devgateway.toolkit.forms.wicket.page.lists;

import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation;
import org.apache.wicket.extensions.markup.html.repeater.data.table.PropertyColumn;
import org.apache.wicket.model.Model;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.devgateway.toolkit.web.security.SecurityConstants;
import org.devgateway.toolkit.forms.wicket.page.user.EditUserPageElevated;
import org.devgateway.toolkit.persistence.dao.Person;
import org.devgateway.toolkit.persistence.service.PersonService;
import org.wicketstuff.annotation.mount.MountPath;

@AuthorizeInstantiation(SecurityConstants.Roles.ROLE_ADMIN)
@MountPath(value = "/listusers")
public class ListUserPage extends AbstractListPage<Person> {

    private static final long serialVersionUID = 3529738250403399032L;

    @SpringBean
    private PersonService personService;

    public ListUserPage(final PageParameters pageParameters) {
        super(pageParameters);

        this.jpaService = personService;

        this.editPageClass = EditUserPageElevated.class;
        columns.add(new PropertyColumn<>(new Model<>("Name"), "username", "username"));
        columns.add(new PropertyColumn<>(new Model<>("Group"), "group", "group"));
        columns.add(new PropertyColumn<>(new Model<>("Roles"), "roles", "roles"));
    }

    @Override
    protected void onInitialize() {
        super.onInitialize();

        // enable excel download
        excelForm.setVisibilityAllowed(true);
    }
}


text:
Comsci COOP

                     <input type="text" class="form-control" placeholder="Search...">

                       <button class="btn btn-primary" type="button">Search</button>

                      My Account

Profile

Logout


text: The "matcher" example from Go in Action, recreated.


text:
package util;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import junit.framework.Assert;

public class PrivateAccessor {
	public static Object invokePrivateMethod(Object o, String methodName,
			Object[] params) {
		Assert.assertNotNull(o);
		Assert.assertNotNull(methodName);
		Assert.assertNotNull(params);

		for (Method method : o.getClass().getDeclaredMethods()) {
			if (methodName.equals(method.getName())) {
				try {
					method.setAccessible(true);
					return method.invoke(o, params);
				} catch (IllegalAccessException ex) {
					Assert.fail("IllegalAccessException accessing "
							+ methodName);
				} catch (InvocationTargetException ite) {
					Assert.fail("InvocationTargetException accessing "
							+ methodName);
				}
			}
		}
		Assert.fail("Method '" + methodName + "' not found");
		return null;
	}

	public static Object getPrivateField(Object o, String fieldName) {
		// Check we have valid arguments...
		Assert.assertNotNull(o);
		Assert.assertNotNull(fieldName);

		// Go and find the private field...
		final Field fields[] = o.getClass().getDeclaredFields();
		for (int i = 0; i < fields.length; ++i) {
			if (fieldName.equals(fields[i].getName())) {
				try {
					fields[i].setAccessible(true);
					return fields[i].get(o);
				} catch (IllegalAccessException ex) {
					Assert
							.fail("IllegalAccessException accessing "
									+ fieldName);
				}
			}
		}
		Assert.fail("Field '" + fieldName + "' not found");
		return null;
	}
}


text:
layout: base
title:  'Statistics of Polite in UD_Spanish-AnCora'
udver: '2'
---

## Treebank Statistics: UD_Spanish-AnCora: Features: `Polite`

This feature is universal.
It occurs with 1 different values: `Form`.

56 tokens (0%) have a non-empty value of `Polite`.
4 types (0%) occur at least once with a non-empty value of `Polite`.
1 lemmas (0%) occur at least once with a non-empty value of `Polite`.
The feature is used with 1 part-of-speech tags: <tt>PRON</tt> (56; 0% instances).

### `PRON`

56 <tt>PRON</tt> tokens (0% of all `PRON` tokens) have a non-empty value of `Polite`.

The most frequent other feature values with which `PRON` and `Polite` co-occurred: <tt>Case</tt><tt>=Acc,Nom</tt> (56; 100%), <tt>Gender</tt><tt>=EMPTY</tt> (56; 100%), <tt>Person</tt><tt>=2</tt> (56; 100%), <tt>PrepCase</tt><tt>=EMPTY</tt> (56; 100%), <tt>PronType</tt><tt>=Prs</tt> (56; 100%), <tt>Reflex</tt><tt>=EMPTY</tt> (56; 100%), <tt>Number</tt><tt>=Sing</tt> (49; 88%).

`PRON` tokens may have the following values of `Polite`:

* `Form` (56; 100% of non-empty `Polite`): usted, ustedes
* `EMPTY` (25849): que, se, lo, le, me, donde, nos, uno, quien, la


text:
using UnityEngine;

public class Coin : MonoBehaviour {
	private float velocityRotation = 50;
	private bool clicked = false;

	private void Update() {
		transform.Rotate(Vector3.up * Time.deltaTime * velocityRotation);

		if (clicked) {
			velocityRotation += 50;
			transform.localScale += new Vector3(0, -1f, 0.5f);
			transform.position += Vector3.up * 0.01f;

			if (transform.localScale.y <= 0) {
				Destroy(gameObject);
			}
		}
	}

	public void OnCoinClicked() {
		clicked = true;
		GetComponent<AudioSource>().Play();
	}

}


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

module.exports = rempl.createPublisher('Component Inspector', function(settings, callback) {
  // jscs:disable
  /** @cut */ return callback(null, 'url', 'http://localhost:8000/src/inspector-rempl/subscriber/index.html');
  // jscs:enable

  callback(null, 'script', asset('../../../dist/subscriber.js', true));
});


text:
module Selenium
  module WebDriver
    class DevTools
      class Response

        attr_accessor :code, :body, :headers
        attr_reader :id

        #
        # Creates response from DevTools message.
        # @api private
        #

        def self.from(id, encoded_body, params)
          new(
            id: id,
            code: params['responseStatusCode'],
            body: (Base64.strict_decode64(encoded_body) if encoded_body),
            headers: params.fetch('responseHeaders', []).each_with_object({}) do |header, hash|
              hash[header['name']] = header['value']
            end
          )
        end

        def initialize(id:, code:, body:, headers:)
          @id = id
          @code = code
          @body = body
          @headers = headers
        end

        def ==(other)
          self.class == other.class &&
            id == other.id &&
            code == other.code &&
            body == other.body &&
            headers == other.headers
        end

        def inspect
          %(#<#{self.class.name} @id="#{id}" @code="#{code}")
        end

      end # Response
    end # DevTools
  end # WebDriver
end # Selenium


text:
package org.apache.drill.exec.physical.impl.aggregate;

import org.apache.drill.common.exceptions.UserException;
import org.apache.drill.common.expression.SchemaPath;
import org.apache.drill.exec.cache.VectorAccessibleSerializable;
import org.apache.drill.exec.ops.FragmentContext;
import org.apache.drill.exec.ops.OperatorContext;
import org.apache.drill.exec.physical.impl.spill.SpillSet;
import org.apache.drill.exec.record.BatchSchema;
import org.apache.drill.exec.record.CloseableRecordBatch;
import org.apache.drill.exec.record.TypedFieldId;
import org.apache.drill.exec.record.VectorContainer;
import org.apache.drill.exec.record.VectorWrapper;
import org.apache.drill.exec.record.WritableBatch;
import org.apache.drill.exec.record.selection.SelectionVector2;
import org.apache.drill.exec.record.selection.SelectionVector4;

import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;

/**
 * A class to replace "incoming" - instead scanning a spilled partition file
 */
public class SpilledRecordbatch implements CloseableRecordBatch {
  private VectorContainer container;
  private InputStream spillStream;
  private int spilledBatches;
  private FragmentContext context;
  private BatchSchema schema;
  private OperatorContext oContext;
  private SpillSet spillSet;
  // Path spillStreamPath;
  private String spillFile;
  VectorAccessibleSerializable vas;

  public SpilledRecordbatch(String spillFile,/* Path spillStreamPath,*/ int spilledBatches, FragmentContext context, BatchSchema schema, OperatorContext oContext, SpillSet spillSet) {
    this.context = context;
    this.schema = schema;
    this.spilledBatches = spilledBatches;
    this.oContext = oContext;
    this.spillSet = spillSet;
    //this.spillStreamPath = spillStreamPath;
    this.spillFile = spillFile;
    vas = new VectorAccessibleSerializable(oContext.getAllocator());
    container = vas.get();

    try {
      this.spillStream = this.spillSet.openForInput(spillFile);
    } catch (IOException e) {
      throw UserException.resourceError(e).build(HashAggBatch.logger);
    }

    next(); // initialize the container
  }

  @Override
  public SelectionVector2 getSelectionVector2() {
    throw new UnsupportedOperationException();
  }

  @Override
  public SelectionVector4 getSelectionVector4() {
    throw new UnsupportedOperationException();
  }

  @Override
  public TypedFieldId getValueVectorId(SchemaPath path) {
    return container.getValueVectorId(path);
  }

  @Override
  public VectorWrapper<?> getValueAccessorById(Class<?> clazz, int... ids) {
    return container.getValueAccessorById(clazz, ids);
  }

  @Override
  public Iterator<VectorWrapper<?>> iterator() {
    return container.iterator();
  }

  @Override
  public FragmentContext getContext() { return context; }

  @Override
  public BatchSchema getSchema() { return schema; }

  @Override
  public WritableBatch getWritableBatch() {
    return WritableBatch.get(this);
  }

  @Override
  public VectorContainer getOutgoingContainer() { return container; }

  @Override
  public int getRecordCount() { return container.getRecordCount(); }

  @Override
  public void kill(boolean sendUpstream) {
    this.close(); // delete the current spill file
  }

  /**
   * Read the next batch from the spill file
   *
   * @return IterOutcome
   */
  @Override
  public IterOutcome next() {

    if ( ! context.shouldContinue() ) { return IterOutcome.STOP; }

    if ( spilledBatches <= 0 ) { // no more batches to read in this partition
      this.close();
      return IterOutcome.NONE;
    }

    if ( spillStream == null ) {
      throw new IllegalStateException("Spill stream was null");
    };

    if ( spillSet.getPosition(spillStream)  < 0 ) {
      HashAggTemplate.logger.warn("Position is {} for stream {}", spillSet.getPosition(spillStream), spillStream.toString());
    }

    try {
      if ( container.getNumberOfColumns() > 0 ) { // container already initialized
        // Pass our container to the reader because other classes (e.g. HashAggBatch, HashTable)
        // may have a reference to this container (as an "incoming")
        vas.readFromStreamWithContainer(container, spillStream);
      }
      else { // first time - create a container
        vas.readFromStream(spillStream);
        container = vas.get();
      }
    } catch (IOException e) {
      throw UserException.dataReadError(e).addContext("Failed reading from a spill file").build(HashAggTemplate.logger);
    }

    spilledBatches-- ; // one less batch to read
    return IterOutcome.OK;
  }

  /**
   * Note: ignoring any IO errors (e.g. file not found)
   */
  @Override
  public void close() {
    container.clear();
    try {
      if (spillStream != null) {
        spillStream.close();
        spillStream = null;
      }

      spillSet.delete(spillFile);
    }
    catch (IOException e) {
      /* ignore */
    } finally {
    }
  }
}


text:
.. _payloadtype-com.microsoft.Word:

Microsoft Word
==============

Summary
-------

.. pfm:: /_static/ProfileManifests/Manifests/ManagedPreferencesApplications/com.microsoft.Word.plist


text:
<?xml version="1.0" encoding="utf-8"?>
<TabHost
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/adm_time_ui_tabhost"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical">

        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"/>

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent">

            <LinearLayout
                android:id="@+id/adm_time_ui"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical">
                <LinearLayout
                    android:id="@+id/linearLayout"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_alignParentTop="true"
                    android:orientation="vertical">

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="@string/nome" />

                    <EditText
                        android:id="@+id/nome_equipe"
                        android:layout_width="fill_parent"
                        android:layout_height="wrap_content"
                        android:inputType="text" />

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="@string/dataFundacao" />

                    <EditText
                        android:id="@+id/fundacao_equipe"
                        android:layout_width="fill_parent"
                        android:layout_height="wrap_content"
                        android:inputType="date" />
                    <Button
                        android:id="@+id/mapa_mostra_usuarios"
                        style="?android:attr/buttonStyleSmall"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="Convidar Jogadores" />
                    <ListView
                        android:id="@+id/listaJogadores"
                        android:layout_width="fill_parent"
                        android:layout_height="match_parent"/>

                </LinearLayout>

            </LinearLayout>

            <LinearLayout
                android:id="@+id/adm_time_ui_agenda"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical">

            </LinearLayout>

            <LinearLayout
                android:id="@+id/adm_time_ui_pendentes"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical">

            </LinearLayout>

        </FrameLayout>
    </LinearLayout>

</TabHost>


text:
<template name="Footer">

        Made by Michael Spencer

        University of Hawaii

        Honolulu, HI 96822

</template>


text:
Template[getTemplate('postAuthor')].helpers({
  authorName: function(){
    return getAuthorName(this);
  },
  profileUrl: function(){
    // note: we don't want the post to be re-rendered every time user properties change
    var user = Meteor.users.findOne(this.userId, {reactive: false});
    if(user)
      return getProfileUrl(user);
  }
})


text:
module Tests.IP4 (ip4Tests) where

import Tests.IP4.Fragmentation (fragTests)
import Tests.IP4.Icmp4 (icmp4Tests)
import Tests.IP4.Packet (packetTests)

import Test.Tasty

ip4Tests :: TestTree
ip4Tests  = testGroup "IP4"
  [ packetTests
  , fragTests
  , icmp4Tests
  ]


text:
package org.flamering.sample.chat.login.message;

import com.fasterxml.jackson.annotation.JsonProperty;

public class LogoutRequest {

	private String messageName = "LogoutRequest";

	private String userName = "";

	private String userToken = "";

	@JsonProperty("msg")
	public String getMessageName() {
		return messageName;
	}
	@JsonProperty("msg")
	public void setMessageName(String messageName) {
		this.messageName = messageName;
	}

	@JsonProperty("user_name")
	public String getUserName() {
		return userName;
	}

	@JsonProperty("user_name")
	public void setUserName(String userName) {
		this.userName = userName;
	}

	@JsonProperty("user_token")
	public String getUserToken() {
		return userToken;
	}

	@JsonProperty("user_token")
	public void setUserToken(String userToken) {
		this.userToken = userToken;
	}

}


text:
/**************************************
INCLUDE files for :regular expression comparator
**************************************/
/* +++Date last modified: 05-Jul-1997 */
/*
EPSHeader
File: match.h
Author: J. Kercheval
Created: Sat, 01/05/1991 22:27:18
*/
/*
EPSRevision History
J. Kercheval Wed, 02/20/1991 22:28:37 Released to Public Domain
J. Kercheval Sun, 03/10/1991 18:02:56 add is_valid_pattern
J. Kercheval Sun, 03/10/1991 18:25:48 add error_type in is_valid_pattern
J. Kercheval Sun, 03/10/1991 18:47:47 error return from matche()
J. Kercheval Tue, 03/12/1991 22:24:49 Released as V1.1 to Public Domain
*/
#ifndef MATCH__HPP
#define MATCH__HPP
/*
Wildcard Pattern Matching
*/
#ifndef BOOLEAN
# define BOOLEAN int
# define TRUE 1
# define FALSE 0
#endif
/* match defines */
#define MATCH_PATTERN 6/* bad pattern */
#define MATCH_LITERAL 5/* match failure on literal match */
#define MATCH_RANGE 4/* match failure on [..] construct */
#define MATCH_ABORT 3/* premature end of text string */
#define MATCH_END 2/* premature end of pattern string */
#define MATCH_VALID 1/* valid match */
/* pattern defines */
#define PATTERN_VALID 0/* valid pattern */
#define PATTERN_ESC -1/* literal escape at end of pattern */
#define PATTERN_RANGE -2/* malformed range in [..] construct */
#define PATTERN_CLOSE -3/* no end bracket in [..] construct */
#define PATTERN_EMPTY -4/* [..] construct is empty */
/*----------------------------------------------------------------------------
*
* Match the pattern PATTERN against the string TEXT;
*
*match() returns TRUE if pattern matches, FALSE otherwise.
*matche() returns MATCH_VALID if pattern matches, or an errorcode
*as follows otherwise:
*
*MATCH_PATTERN - bad pattern
*MATCH_LITERAL - match failure on literal mismatch
*MATCH_RANGE- match failure on [..] construct
*MATCH_ABORT- premature end of text string
*MATCH_END - premature end of pattern string
*MATCH_VALID- valid match
*
*
* A match means the entire string TEXT is used up in matching.
*
* In the pattern string:
*`*' matches any sequence of characters (zero or more)
*`?' matches any character
*[SET] matches any character in the specified set,
*[!SET] or [^SET] matches any character not in the specified set.
*
* A set is composed of characters or ranges; a range looks like
* character hyphen character (as in 0-9 or A-Z). [0-9a-zA-Z_] is the
* minimal set of characters allowed in the [..] pattern construct.
* Other characters are allowed (ie. 8 bit characters) if your system
* will support them.
*
* To suppress the special syntactic significance of any of `[]*?!^-\',
* and match the character exactly, precede it with a `\'.
*
----------------------------------------------------------------------------*/
BOOLEAN match( char *pattern, char *text );
int matche( register char *pattern, register char *text );
/*----------------------------------------------------------------------------
*
* Return TRUE if PATTERN has any special wildcard characters
*
----------------------------------------------------------------------------*/
BOOLEAN is_pattern( char *pattern );
/*----------------------------------------------------------------------------
*
* Return TRUE if PATTERN has is a well formed regular expression according
* to the above syntax
*
* error_type is a return code based on the type of pattern error. Zero is
* returned in error_type if the pattern is a valid one. error_type return
* values are as follows:
*
*PATTERN_VALID - pattern is well formed
*PATTERN_ESC- pattern has invalid escape ('\' at end of pattern)
*PATTERN_RANGE - [..] construct has a no end range in a '-' pair (ie [a-])
*PATTERN_CLOSE - [..] construct has no end bracket (ie [abc-g )
*PATTERN_EMPTY - [..] construct is empty (ie [])
*
----------------------------------------------------------------------------*/
BOOLEAN is_valid_pattern( char *pattern, int *error_type );
#endif /* MATCH__H */


text:
module CurrentCart
  private
    def set_cart
      @cart = Cart.find(session[:cart_id])
    rescue ActiveRecord::RecordNotFound
      @cart = Cart.create
      session[:cart_id] = @cart.id
    end
end


text:
using System.Collections.Generic;
using Newtonsoft.Json;
using Wox.Infrastructure.Storage;

namespace Wox.Plugin.CMD
{
    public class CMDStorage : JsonStrorage<CMDStorage>
    {
        [JsonProperty]
        public bool ReplaceWinR { get; set; }

        [JsonProperty]
        public bool LeaveCmdOpen { get; set; }

        [JsonProperty]
        public Dictionary<string, int> CMDHistory = new Dictionary<string, int>();

        protected override string FileName { get; } = "CMDHistory";

        protected override CMDStorage LoadDefault()
        {
            ReplaceWinR = true;
            return this;
        }

        public void AddCmdHistory(string cmdName)
        {
            if (CMDHistory.ContainsKey(cmdName))
            {
                CMDHistory[cmdName] += 1;
            }
            else
            {
                CMDHistory.Add(cmdName, 1);
            }
            Save();
        }

    }
}


text:
namespace domain_reliability {

namespace {

const struct NetErrorMapping {
  int net_error;
  const char* beacon_status;
} net_error_map[] = {
    {net::OK, "ok"},
    {net::ERR_ABORTED, "aborted"},
    {net::ERR_TIMED_OUT, "tcp.connection.timed_out"},
    {net::ERR_CONNECTION_CLOSED, "tcp.connection.closed"},
    {net::ERR_CONNECTION_RESET, "tcp.connection.reset"},
    {net::ERR_CONNECTION_REFUSED, "tcp.connection.refused"},
    {net::ERR_CONNECTION_ABORTED, "tcp.connection.aborted"},
    {net::ERR_CONNECTION_FAILED, "tcp.connection.failed"},
    {net::ERR_NAME_NOT_RESOLVED, "dns"},
    {net::ERR_SSL_PROTOCOL_ERROR, "ssl.protocol.error"},
    {net::ERR_ADDRESS_INVALID, "tcp.connection.address_invalid"},
    {net::ERR_ADDRESS_UNREACHABLE, "tcp.connection.address_unreachable"},
    {net::ERR_CONNECTION_TIMED_OUT, "tcp.connection.timed_out"},
    {net::ERR_NAME_RESOLUTION_FAILED, "dns"},
    {net::ERR_SSL_PINNED_KEY_NOT_IN_CERT_CHAIN,
     "ssl.cert.pinned_key_not_in_cert_chain"},
    {net::ERR_CERT_COMMON_NAME_INVALID, "ssl.cert.name_invalid"},
    {net::ERR_CERT_DATE_INVALID, "ssl.cert.date_invalid"},
    {net::ERR_CERT_AUTHORITY_INVALID, "ssl.cert.authority_invalid"},
    {net::ERR_CERT_KNOWN_INTERCEPTION_BLOCKED, "ssl.cert.authority_invalid"},
    {net::ERR_CERT_REVOKED, "ssl.cert.revoked"},
    {net::ERR_CERT_INVALID, "ssl.cert.invalid"},
    {net::ERR_EMPTY_RESPONSE, "http.response.empty"},
    {net::ERR_HTTP2_PING_FAILED, "spdy.ping_failed"},
    {net::ERR_HTTP2_PROTOCOL_ERROR, "spdy.protocol"},
    {net::ERR_QUIC_PROTOCOL_ERROR, "quic.protocol"},
    {net::ERR_DNS_MALFORMED_RESPONSE, "dns.protocol"},
    {net::ERR_DNS_SERVER_FAILED, "dns.server"},
    {net::ERR_DNS_TIMED_OUT, "dns.timed_out"},
    {net::ERR_INSECURE_RESPONSE, "ssl"},
    {net::ERR_CONTENT_LENGTH_MISMATCH, "http.response.content_length_mismatch"},
    {net::ERR_INCOMPLETE_CHUNKED_ENCODING,
     "http.response.incomplete_chunked_encoding"},
    {net::ERR_SSL_VERSION_OR_CIPHER_MISMATCH, "ssl.version_or_cipher_mismatch"},
    {net::ERR_BAD_SSL_CLIENT_AUTH_CERT, "ssl.bad_client_auth_cert"},
    {net::ERR_INVALID_CHUNKED_ENCODING,
     "http.response.invalid_chunked_encoding"},
    {net::ERR_RESPONSE_HEADERS_TRUNCATED, "http.response.headers.truncated"},
    {net::ERR_REQUEST_RANGE_NOT_SATISFIABLE,
     "http.request.range_not_satisfiable"},
    {net::ERR_INVALID_RESPONSE, "http.response.invalid"},
    {net::ERR_RESPONSE_HEADERS_MULTIPLE_CONTENT_DISPOSITION,
     "http.response.headers.multiple_content_disposition"},
    {net::ERR_RESPONSE_HEADERS_MULTIPLE_CONTENT_LENGTH,
     "http.response.headers.multiple_content_length"},
    {net::ERR_SSL_UNRECOGNIZED_NAME_ALERT, "ssl.unrecognized_name_alert"}};

bool CanReportFullBeaconURLToCollector(const GURL& beacon_url,
                                       const GURL& collector_url) {
  return beacon_url.DeprecatedGetOriginAsURL() ==
         collector_url.DeprecatedGetOriginAsURL();
}

}  // namespace

// static
bool GetDomainReliabilityBeaconStatus(
    int net_error,
    int http_response_code,
    std::string* beacon_status_out) {
  if (net_error == net::OK) {
    if (http_response_code >= 400 && http_response_code < 600)
      *beacon_status_out = "http.error";
    else
      *beacon_status_out = "ok";
    return true;
  }

  // TODO(juliatuttle): Consider sorting and using binary search?
  for (size_t i = 0; i < std::size(net_error_map); i++) {
    if (net_error_map[i].net_error == net_error) {
      *beacon_status_out = net_error_map[i].beacon_status;
      return true;
    }
  }
  return false;
}

// TODO(juliatuttle): Consider using ALPN instead, if there's a good way to
//                    differentiate HTTP and HTTPS.
std::string GetDomainReliabilityProtocol(
    net::HttpResponseInfo::ConnectionInfo connection_info,
    bool ssl_info_populated) {
  switch (net::HttpResponseInfo::ConnectionInfoToCoarse(connection_info)) {
    case net::HttpResponseInfo::CONNECTION_INFO_COARSE_HTTP1:
      return ssl_info_populated ? "HTTPS" : "HTTP";
    case net::HttpResponseInfo::CONNECTION_INFO_COARSE_HTTP2:
      return "SPDY";
    case net::HttpResponseInfo::CONNECTION_INFO_COARSE_QUIC:
      return "QUIC";
    case net::HttpResponseInfo::CONNECTION_INFO_COARSE_OTHER:
      return "";
  }
  NOTREACHED();
  return "";
}

DomainReliabilityUploader::UploadResult GetUploadResultFromResponseDetails(
    int net_error,
    int http_response_code,
    base::TimeDelta retry_after) {
  DomainReliabilityUploader::UploadResult result;
  if (net_error == net::OK && http_response_code == 200) {
    result.status = DomainReliabilityUploader::UploadResult::SUCCESS;
    return result;
  }

  if (net_error == net::OK && http_response_code == 503 &&
      !retry_after.is_zero()) {
    result.status = DomainReliabilityUploader::UploadResult::RETRY_AFTER;
    result.retry_after = retry_after;
    return result;
  }

  result.status = DomainReliabilityUploader::UploadResult::FAILURE;
  return result;
}

// N.B. This uses a std::vector<std::unique_ptr<>> because that's what
// JSONValueConverter uses for repeated fields of any type, and Config uses
// JSONValueConverter to parse JSON configs.
GURL SanitizeURLForReport(
    const GURL& beacon_url,
    const GURL& collector_url,
    const std::vector<std::unique_ptr<std::string>>& path_prefixes) {
  if (CanReportFullBeaconURLToCollector(beacon_url, collector_url))
    return beacon_url.GetAsReferrer();

  std::string path = beacon_url.path();
  const std::string empty_path;
  const std::string* longest_path_prefix = &empty_path;
  for (const auto& path_prefix : path_prefixes) {
    if (path.substr(0, path_prefix->length()) == *path_prefix &&
        path_prefix->length() > longest_path_prefix->length()) {
      longest_path_prefix = path_prefix.get();
    }
  }

  GURL::Replacements replacements;
  replacements.ClearUsername();
  replacements.ClearPassword();
  replacements.SetPathStr(*longest_path_prefix);
  replacements.ClearQuery();
  replacements.ClearRef();
  return beacon_url.ReplaceComponents(replacements);
}

namespace {

class ActualTimer : public MockableTime::Timer {
 public:
  ActualTimer() {}
  ~ActualTimer() override {}

  // MockableTime::Timer implementation:
  void Start(const base::Location& posted_from,
             base::TimeDelta delay,
             base::OnceClosure user_task) override {
    base_timer_.Start(posted_from, delay, std::move(user_task));
  }

  void Stop() override { base_timer_.Stop(); }

  bool IsRunning() override { return base_timer_.IsRunning(); }

 private:
  base::OneShotTimer base_timer_;
};

}  // namespace

MockableTime::Timer::~Timer() {}
MockableTime::Timer::Timer() {}

MockableTime::~MockableTime() {}
MockableTime::MockableTime() {}

ActualTime::ActualTime() {}
ActualTime::~ActualTime() {}

base::Time ActualTime::Now() const {
  return base::Time::Now();
}
base::TimeTicks ActualTime::NowTicks() const {
  return base::TimeTicks::Now();
}

std::unique_ptr<MockableTime::Timer> ActualTime::CreateTimer() {
  return std::unique_ptr<MockableTime::Timer>(new ActualTimer());
}

const base::TickClock* ActualTime::AsTickClock() const {
  return base::DefaultTickClock::GetInstance();
}

}  // namespace domain_reliability


text:
package runtime

import (
	encodingjson "encoding/json"
	"fmt"
	"math"
	"os"
	"reflect"
	"strconv"
	"strings"
	"sync"
	"sync/atomic"
	"time"

	"k8s.io/apimachinery/pkg/conversion"
	"k8s.io/apimachinery/pkg/util/json"
	utilruntime "k8s.io/apimachinery/pkg/util/runtime"
	"sigs.k8s.io/structured-merge-diff/v3/value"

	"k8s.io/klog"
)

// UnstructuredConverter is an interface for converting between interface{}
// and map[string]interface representation.
type UnstructuredConverter interface {
	ToUnstructured(obj interface{}) (map[string]interface{}, error)
	FromUnstructured(u map[string]interface{}, obj interface{}) error
}

type structField struct {
	structType reflect.Type
	field      int
}

type fieldInfo struct {
	name      string
	nameValue reflect.Value
	omitempty bool
}

type fieldsCacheMap map[structField]*fieldInfo

type fieldsCache struct {
	sync.Mutex
	value atomic.Value
}

func newFieldsCache() *fieldsCache {
	cache := &fieldsCache{}
	cache.value.Store(make(fieldsCacheMap))
	return cache
}

var (
	mapStringInterfaceType = reflect.TypeOf(map[string]interface{}{})
	stringType             = reflect.TypeOf(string(""))
	fieldCache             = newFieldsCache()

	// DefaultUnstructuredConverter performs unstructured to Go typed object conversions.
	DefaultUnstructuredConverter = &unstructuredConverter{
		mismatchDetection: parseBool(os.Getenv("KUBE_PATCH_CONVERSION_DETECTOR")),
		comparison: conversion.EqualitiesOrDie(
			func(a, b time.Time) bool {
				return a.UTC() == b.UTC()
			},
		),
	}
)

func parseBool(key string) bool {
	if len(key) == 0 {
		return false
	}
	value, err := strconv.ParseBool(key)
	if err != nil {
		utilruntime.HandleError(fmt.Errorf("couldn't parse '%s' as bool for unstructured mismatch detection", key))
	}
	return value
}

// unstructuredConverter knows how to convert between interface{} and
// Unstructured in both ways.
type unstructuredConverter struct {
	// If true, we will be additionally running conversion via json
	// to ensure that the result is true.
	// This is supposed to be set only in tests.
	mismatchDetection bool
	// comparison is the default test logic used to compare
	comparison conversion.Equalities
}

// NewTestUnstructuredConverter creates an UnstructuredConverter that accepts JSON typed maps and translates them
// to Go types via reflection. It performs mismatch detection automatically and is intended for use by external
// test tools. Use DefaultUnstructuredConverter if you do not explicitly need mismatch detection.
func NewTestUnstructuredConverter(comparison conversion.Equalities) UnstructuredConverter {
	return &unstructuredConverter{
		mismatchDetection: true,
		comparison:        comparison,
	}
}

// FromUnstructured converts an object from map[string]interface{} representation into a concrete type.
// It uses encoding/json/Unmarshaler if object implements it or reflection if not.
func (c *unstructuredConverter) FromUnstructured(u map[string]interface{}, obj interface{}) error {
	t := reflect.TypeOf(obj)
	value := reflect.ValueOf(obj)
	if t.Kind() != reflect.Ptr || value.IsNil() {
		return fmt.Errorf("FromUnstructured requires a non-nil pointer to an object, got %v", t)
	}
	err := fromUnstructured(reflect.ValueOf(u), value.Elem())
	if c.mismatchDetection {
		newObj := reflect.New(t.Elem()).Interface()
		newErr := fromUnstructuredViaJSON(u, newObj)
		if (err != nil) != (newErr != nil) {
			klog.Fatalf("FromUnstructured unexpected error for %v: error: %v", u, err)
		}
		if err == nil && !c.comparison.DeepEqual(obj, newObj) {
			klog.Fatalf("FromUnstructured mismatch\nobj1: %#v\nobj2: %#v", obj, newObj)
		}
	}
	return err
}

func fromUnstructuredViaJSON(u map[string]interface{}, obj interface{}) error {
	data, err := json.Marshal(u)
	if err != nil {
		return err
	}
	return json.Unmarshal(data, obj)
}

func fromUnstructured(sv, dv reflect.Value) error {
	sv = unwrapInterface(sv)
	if !sv.IsValid() {
		dv.Set(reflect.Zero(dv.Type()))
		return nil
	}
	st, dt := sv.Type(), dv.Type()

	switch dt.Kind() {
	case reflect.Map, reflect.Slice, reflect.Ptr, reflect.Struct, reflect.Interface:
		// Those require non-trivial conversion.
	default:
		// This should handle all simple types.
		if st.AssignableTo(dt) {
			dv.Set(sv)
			return nil
		}
		// We cannot simply use "ConvertibleTo", as JSON doesn't support conversions
		// between those four groups: bools, integers, floats and string. We need to
		// do the same.
		if st.ConvertibleTo(dt) {
			switch st.Kind() {
			case reflect.String:
				switch dt.Kind() {
				case reflect.String:
					dv.Set(sv.Convert(dt))
					return nil
				}
			case reflect.Bool:
				switch dt.Kind() {
				case reflect.Bool:
					dv.Set(sv.Convert(dt))
					return nil
				}
			case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
				reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
				switch dt.Kind() {
				case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
					reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
					dv.Set(sv.Convert(dt))
					return nil
				}
			case reflect.Float32, reflect.Float64:
				switch dt.Kind() {
				case reflect.Float32, reflect.Float64:
					dv.Set(sv.Convert(dt))
					return nil
				}
				if sv.Float() == math.Trunc(sv.Float()) {
					dv.Set(sv.Convert(dt))
					return nil
				}
			}
			return fmt.Errorf("cannot convert %s to %s", st.String(), dt.String())
		}
	}

	// Check if the object has a custom JSON marshaller/unmarshaller.
	entry := value.TypeReflectEntryOf(dv.Type())
	if entry.CanConvertFromUnstructured() {
		return entry.FromUnstructured(sv, dv)
	}

	switch dt.Kind() {
	case reflect.Map:
		return mapFromUnstructured(sv, dv)
	case reflect.Slice:
		return sliceFromUnstructured(sv, dv)
	case reflect.Ptr:
		return pointerFromUnstructured(sv, dv)
	case reflect.Struct:
		return structFromUnstructured(sv, dv)
	case reflect.Interface:
		return interfaceFromUnstructured(sv, dv)
	default:
		return fmt.Errorf("unrecognized type: %v", dt.Kind())
	}
}

func fieldInfoFromField(structType reflect.Type, field int) *fieldInfo {
	fieldCacheMap := fieldCache.value.Load().(fieldsCacheMap)
	if info, ok := fieldCacheMap[structField{structType, field}]; ok {
		return info
	}

	// Cache miss - we need to compute the field name.
	info := &fieldInfo{}
	typeField := structType.Field(field)
	jsonTag := typeField.Tag.Get("json")
	if len(jsonTag) == 0 {
		// Make the first character lowercase.
		if typeField.Name == "" {
			info.name = typeField.Name
		} else {
			info.name = strings.ToLower(typeField.Name[:1]) + typeField.Name[1:]
		}
	} else {
		items := strings.Split(jsonTag, ",")
		info.name = items[0]
		for i := range items {
			if items[i] == "omitempty" {
				info.omitempty = true
				break
			}
		}
	}
	info.nameValue = reflect.ValueOf(info.name)

	fieldCache.Lock()
	defer fieldCache.Unlock()
	fieldCacheMap = fieldCache.value.Load().(fieldsCacheMap)
	newFieldCacheMap := make(fieldsCacheMap)
	for k, v := range fieldCacheMap {
		newFieldCacheMap[k] = v
	}
	newFieldCacheMap[structField{structType, field}] = info
	fieldCache.value.Store(newFieldCacheMap)
	return info
}

func unwrapInterface(v reflect.Value) reflect.Value {
	for v.Kind() == reflect.Interface {
		v = v.Elem()
	}
	return v
}

func mapFromUnstructured(sv, dv reflect.Value) error {
	st, dt := sv.Type(), dv.Type()
	if st.Kind() != reflect.Map {
		return fmt.Errorf("cannot restore map from %v", st.Kind())
	}

	if !st.Key().AssignableTo(dt.Key()) && !st.Key().ConvertibleTo(dt.Key()) {
		return fmt.Errorf("cannot copy map with non-assignable keys: %v %v", st.Key(), dt.Key())
	}

	if sv.IsNil() {
		dv.Set(reflect.Zero(dt))
		return nil
	}
	dv.Set(reflect.MakeMap(dt))
	for _, key := range sv.MapKeys() {
		value := reflect.New(dt.Elem()).Elem()
		if val := unwrapInterface(sv.MapIndex(key)); val.IsValid() {
			if err := fromUnstructured(val, value); err != nil {
				return err
			}
		} else {
			value.Set(reflect.Zero(dt.Elem()))
		}
		if st.Key().AssignableTo(dt.Key()) {
			dv.SetMapIndex(key, value)
		} else {
			dv.SetMapIndex(key.Convert(dt.Key()), value)
		}
	}
	return nil
}

func sliceFromUnstructured(sv, dv reflect.Value) error {
	st, dt := sv.Type(), dv.Type()
	if st.Kind() == reflect.String && dt.Elem().Kind() == reflect.Uint8 {
		// We store original []byte representation as string.
		// This conversion is allowed, but we need to be careful about
		// marshaling data appropriately.
		if len(sv.Interface().(string)) > 0 {
			marshalled, err := json.Marshal(sv.Interface())
			if err != nil {
				return fmt.Errorf("error encoding %s to json: %v", st, err)
			}
			// TODO: Is this Unmarshal needed?
			var data []byte
			err = json.Unmarshal(marshalled, &data)
			if err != nil {
				return fmt.Errorf("error decoding from json: %v", err)
			}
			dv.SetBytes(data)
		} else {
			dv.Set(reflect.Zero(dt))
		}
		return nil
	}
	if st.Kind() != reflect.Slice {
		return fmt.Errorf("cannot restore slice from %v", st.Kind())
	}

	if sv.IsNil() {
		dv.Set(reflect.Zero(dt))
		return nil
	}
	dv.Set(reflect.MakeSlice(dt, sv.Len(), sv.Cap()))
	for i := 0; i < sv.Len(); i++ {
		if err := fromUnstructured(sv.Index(i), dv.Index(i)); err != nil {
			return err
		}
	}
	return nil
}

func pointerFromUnstructured(sv, dv reflect.Value) error {
	st, dt := sv.Type(), dv.Type()

	if st.Kind() == reflect.Ptr && sv.IsNil() {
		dv.Set(reflect.Zero(dt))
		return nil
	}
	dv.Set(reflect.New(dt.Elem()))
	switch st.Kind() {
	case reflect.Ptr, reflect.Interface:
		return fromUnstructured(sv.Elem(), dv.Elem())
	default:
		return fromUnstructured(sv, dv.Elem())
	}
}

func structFromUnstructured(sv, dv reflect.Value) error {
	st, dt := sv.Type(), dv.Type()
	if st.Kind() != reflect.Map {
		return fmt.Errorf("cannot restore struct from: %v", st.Kind())
	}

	for i := 0; i < dt.NumField(); i++ {
		fieldInfo := fieldInfoFromField(dt, i)
		fv := dv.Field(i)

		if len(fieldInfo.name) == 0 {
			// This field is inlined.
			if err := fromUnstructured(sv, fv); err != nil {
				return err
			}
		} else {
			value := unwrapInterface(sv.MapIndex(fieldInfo.nameValue))
			if value.IsValid() {
				if err := fromUnstructured(value, fv); err != nil {
					return err
				}
			} else {
				fv.Set(reflect.Zero(fv.Type()))
			}
		}
	}
	return nil
}

func interfaceFromUnstructured(sv, dv reflect.Value) error {
	// TODO: Is this conversion safe?
	dv.Set(sv)
	return nil
}

// ToUnstructured converts an object into map[string]interface{} representation.
// It uses encoding/json/Marshaler if object implements it or reflection if not.
func (c *unstructuredConverter) ToUnstructured(obj interface{}) (map[string]interface{}, error) {
	var u map[string]interface{}
	var err error
	if unstr, ok := obj.(Unstructured); ok {
		u = unstr.UnstructuredContent()
	} else {
		t := reflect.TypeOf(obj)
		value := reflect.ValueOf(obj)
		if t.Kind() != reflect.Ptr || value.IsNil() {
			return nil, fmt.Errorf("ToUnstructured requires a non-nil pointer to an object, got %v", t)
		}
		u = map[string]interface{}{}
		err = toUnstructured(value.Elem(), reflect.ValueOf(&u).Elem())
	}
	if c.mismatchDetection {
		newUnstr := map[string]interface{}{}
		newErr := toUnstructuredViaJSON(obj, &newUnstr)
		if (err != nil) != (newErr != nil) {
			klog.Fatalf("ToUnstructured unexpected error for %v: error: %v; newErr: %v", obj, err, newErr)
		}
		if err == nil && !c.comparison.DeepEqual(u, newUnstr) {
			klog.Fatalf("ToUnstructured mismatch\nobj1: %#v\nobj2: %#v", u, newUnstr)
		}
	}
	if err != nil {
		return nil, err
	}
	return u, nil
}

// DeepCopyJSON deep copies the passed value, assuming it is a valid JSON representation i.e. only contains
// types produced by json.Unmarshal() and also int64.
// bool, int64, float64, string, []interface{}, map[string]interface{}, json.Number and nil
func DeepCopyJSON(x map[string]interface{}) map[string]interface{} {
	return DeepCopyJSONValue(x).(map[string]interface{})
}

// DeepCopyJSONValue deep copies the passed value, assuming it is a valid JSON representation i.e. only contains
// types produced by json.Unmarshal() and also int64.
// bool, int64, float64, string, []interface{}, map[string]interface{}, json.Number and nil
func DeepCopyJSONValue(x interface{}) interface{} {
	switch x := x.(type) {
	case map[string]interface{}:
		if x == nil {
			// Typed nil - an interface{} that contains a type map[string]interface{} with a value of nil
			return x
		}
		clone := make(map[string]interface{}, len(x))
		for k, v := range x {
			clone[k] = DeepCopyJSONValue(v)
		}
		return clone
	case []interface{}:
		if x == nil {
			// Typed nil - an interface{} that contains a type []interface{} with a value of nil
			return x
		}
		clone := make([]interface{}, len(x))
		for i, v := range x {
			clone[i] = DeepCopyJSONValue(v)
		}
		return clone
	case string, int64, bool, float64, nil, encodingjson.Number:
		return x
	default:
		panic(fmt.Errorf("cannot deep copy %T", x))
	}
}

func toUnstructuredViaJSON(obj interface{}, u *map[string]interface{}) error {
	data, err := json.Marshal(obj)
	if err != nil {
		return err
	}
	return json.Unmarshal(data, u)
}

func toUnstructured(sv, dv reflect.Value) error {
	// Check if the object has a custom string converter.
	entry := value.TypeReflectEntryOf(sv.Type())
	if entry.CanConvertToUnstructured() {
		v, err := entry.ToUnstructured(sv)
		if err != nil {
			return err
		}
		if v != nil {
			dv.Set(reflect.ValueOf(v))
		}
		return nil
	}
	st := sv.Type()
	switch st.Kind() {
	case reflect.String:
		dv.Set(reflect.ValueOf(sv.String()))
		return nil
	case reflect.Bool:
		dv.Set(reflect.ValueOf(sv.Bool()))
		return nil
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		dv.Set(reflect.ValueOf(sv.Int()))
		return nil
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
		uVal := sv.Uint()
		if uVal > math.MaxInt64 {
			return fmt.Errorf("unsigned value %d does not fit into int64 (overflow)", uVal)
		}
		dv.Set(reflect.ValueOf(int64(uVal)))
		return nil
	case reflect.Float32, reflect.Float64:
		dv.Set(reflect.ValueOf(sv.Float()))
		return nil
	case reflect.Map:
		return mapToUnstructured(sv, dv)
	case reflect.Slice:
		return sliceToUnstructured(sv, dv)
	case reflect.Ptr:
		return pointerToUnstructured(sv, dv)
	case reflect.Struct:
		return structToUnstructured(sv, dv)
	case reflect.Interface:
		return interfaceToUnstructured(sv, dv)
	default:
		return fmt.Errorf("unrecognized type: %v", st.Kind())
	}
}

func mapToUnstructured(sv, dv reflect.Value) error {
	st, dt := sv.Type(), dv.Type()
	if sv.IsNil() {
		dv.Set(reflect.Zero(dt))
		return nil
	}
	if dt.Kind() == reflect.Interface && dv.NumMethod() == 0 {
		if st.Key().Kind() == reflect.String {
			switch st.Elem().Kind() {
			// TODO It should be possible to reuse the slice for primitive types.
			// However, it is panicing in the following form.
			// case reflect.String, reflect.Bool,
			// 	reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
			// 	reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
			// 	sv.Set(sv)
			// 	return nil
			default:
				// We need to do a proper conversion.
			}
		}
		dv.Set(reflect.MakeMap(mapStringInterfaceType))
		dv = dv.Elem()
		dt = dv.Type()
	}
	if dt.Kind() != reflect.Map {
		return fmt.Errorf("cannot convert struct to: %v", dt.Kind())
	}

	if !st.Key().AssignableTo(dt.Key()) && !st.Key().ConvertibleTo(dt.Key()) {
		return fmt.Errorf("cannot copy map with non-assignable keys: %v %v", st.Key(), dt.Key())
	}

	for _, key := range sv.MapKeys() {
		value := reflect.New(dt.Elem()).Elem()
		if err := toUnstructured(sv.MapIndex(key), value); err != nil {
			return err
		}
		if st.Key().AssignableTo(dt.Key()) {
			dv.SetMapIndex(key, value)
		} else {
			dv.SetMapIndex(key.Convert(dt.Key()), value)
		}
	}
	return nil
}

func sliceToUnstructured(sv, dv reflect.Value) error {
	st, dt := sv.Type(), dv.Type()
	if sv.IsNil() {
		dv.Set(reflect.Zero(dt))
		return nil
	}
	if st.Elem().Kind() == reflect.Uint8 {
		dv.Set(reflect.New(stringType))
		data, err := json.Marshal(sv.Bytes())
		if err != nil {
			return err
		}
		var result string
		if err = json.Unmarshal(data, &result); err != nil {
			return err
		}
		dv.Set(reflect.ValueOf(result))
		return nil
	}
	if dt.Kind() == reflect.Interface && dv.NumMethod() == 0 {
		switch st.Elem().Kind() {
		// TODO It should be possible to reuse the slice for primitive types.
		// However, it is panicing in the following form.
		// case reflect.String, reflect.Bool,
		// 	reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
		// 	reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
		// 	sv.Set(sv)
		// 	return nil
		default:
			// We need to do a proper conversion.
			dv.Set(reflect.MakeSlice(reflect.SliceOf(dt), sv.Len(), sv.Cap()))
			dv = dv.Elem()
			dt = dv.Type()
		}
	}
	if dt.Kind() != reflect.Slice {
		return fmt.Errorf("cannot convert slice to: %v", dt.Kind())
	}
	for i := 0; i < sv.Len(); i++ {
		if err := toUnstructured(sv.Index(i), dv.Index(i)); err != nil {
			return err
		}
	}
	return nil
}

func pointerToUnstructured(sv, dv reflect.Value) error {
	if sv.IsNil() {
		// We're done - we don't need to store anything.
		return nil
	}
	return toUnstructured(sv.Elem(), dv)
}

func isZero(v reflect.Value) bool {
	switch v.Kind() {
	case reflect.Array, reflect.String:
		return v.Len() == 0
	case reflect.Bool:
		return !v.Bool()
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		return v.Int() == 0
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
		return v.Uint() == 0
	case reflect.Float32, reflect.Float64:
		return v.Float() == 0
	case reflect.Map, reflect.Slice:
		// TODO: It seems that 0-len maps are ignored in it.
		return v.IsNil() || v.Len() == 0
	case reflect.Ptr, reflect.Interface:
		return v.IsNil()
	}
	return false
}

func structToUnstructured(sv, dv reflect.Value) error {
	st, dt := sv.Type(), dv.Type()
	if dt.Kind() == reflect.Interface && dv.NumMethod() == 0 {
		dv.Set(reflect.MakeMapWithSize(mapStringInterfaceType, st.NumField()))
		dv = dv.Elem()
		dt = dv.Type()
	}
	if dt.Kind() != reflect.Map {
		return fmt.Errorf("cannot convert struct to: %v", dt.Kind())
	}
	realMap := dv.Interface().(map[string]interface{})

	for i := 0; i < st.NumField(); i++ {
		fieldInfo := fieldInfoFromField(st, i)
		fv := sv.Field(i)

		if fieldInfo.name == "-" {
			// This field should be skipped.
			continue
		}
		if fieldInfo.omitempty && isZero(fv) {
			// omitempty fields should be ignored.
			continue
		}
		if len(fieldInfo.name) == 0 {
			// This field is inlined.
			if err := toUnstructured(fv, dv); err != nil {
				return err
			}
			continue
		}
		switch fv.Type().Kind() {
		case reflect.String:
			realMap[fieldInfo.name] = fv.String()
		case reflect.Bool:
			realMap[fieldInfo.name] = fv.Bool()
		case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
			realMap[fieldInfo.name] = fv.Int()
		case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
			realMap[fieldInfo.name] = fv.Uint()
		case reflect.Float32, reflect.Float64:
			realMap[fieldInfo.name] = fv.Float()
		default:
			subv := reflect.New(dt.Elem()).Elem()
			if err := toUnstructured(fv, subv); err != nil {
				return err
			}
			dv.SetMapIndex(fieldInfo.nameValue, subv)
		}
	}
	return nil
}

func interfaceToUnstructured(sv, dv reflect.Value) error {
	if !sv.IsValid() || sv.IsNil() {
		dv.Set(reflect.Zero(dv.Type()))
		return nil
	}
	return toUnstructured(sv.Elem(), dv)
}


text:
namespace google {
namespace cloud {
namespace bigtable {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN
// NOLINTNEXTLINE(readability-identifier-naming)
::google::bigtable::admin::v2::CreateTableRequest TableConfig::as_proto() && {
  // As a challenge, we implement the strong exception guarantee in this
  // function.
  // First create a temporary value to hold intermediate computations.
  ::google::bigtable::admin::v2::CreateTableRequest tmp;
  auto& table = *tmp.mutable_table();
  // Make sure there are nodes to receive all the values in column_families_.
  auto& families = *table.mutable_column_families();
  for (auto const& kv : column_families_) {
    families[kv.first].mutable_gc_rule()->Clear();
  }
  // Make sure there is space to receive all the values in initial_splits_.
  tmp.mutable_initial_splits()->Reserve(
      static_cast<int>(initial_splits_.size()));
  // Copy the granularity.
  table.set_granularity(timestamp_granularity());

  // None of the operations that follow can fail, they are all `noexcept`:
  for (auto& kv : column_families_) {
    *families[kv.first].mutable_gc_rule() = std::move(kv.second).as_proto();
  }
  for (auto& split : initial_splits_) {
    tmp.add_initial_splits()->set_key(std::move(split));
  }
  initial_splits_.clear();
  column_families_.clear();
  granularity_ = TIMESTAMP_GRANULARITY_UNSPECIFIED;
  return tmp;
}

// Disable clang-tidy warnings for these two definitions. clang-tidy is confused
// it claims, for example:
//   error: redundant 'MILLIS' declaration
//   [readability-redundant-declaration,-warnings-as-errors]
// But these are not declarations, these are definitions of variables that are
// odr-used in at least the tests:
//    http://en.cppreference.com/w/cpp/language/definition
// In C++17 these would be inline variables and we would not care, but alas! we
// are sticking to C++11 (for good reasons).
constexpr TableConfig::TimestampGranularity TableConfig::MILLIS;  // NOLINT
constexpr TableConfig::TimestampGranularity
    TableConfig::TIMESTAMP_GRANULARITY_UNSPECIFIED;  // NOLINT

GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
}  // namespace bigtable
}  // namespace cloud
}  // namespace google


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Revis. gen. pl. (Leipzig) 3: 446 (1898)

#### Original name
Lachnum phaeomorphum Rehm

### Remarks
null


text:
import wx
import wx.lib.buttons  as  buttons

import images

#----------------------------------------------------------------------

class TestPanel(wx.Panel):
    def __init__(self, parent, log):
        wx.Panel.__init__(self, parent, -1)
        self.log = log
        ##self.SetBackgroundColour("sky blue")

        sizer = wx.FlexGridSizer(cols=3, hgap=20, vgap=20)

        # A regular button, selected as the default button
        b = wx.Button(self, -1, "A real button")
        b.SetDefault()
        self.Bind(wx.EVT_BUTTON, self.OnButton, b)
        sizer.Add(b)

        # Same thing, but NOT set as the default button
        b = wx.Button(self, -1, "non-default")
        self.Bind(wx.EVT_BUTTON, self.OnButton, b)
        sizer.Add(b)
        sizer.Add((10,10))

        # Plain old text button based off GenButton()
        b = buttons.GenButton(self, -1, 'Hello')
        self.Bind(wx.EVT_BUTTON, self.OnButton, b)
        sizer.Add(b)

        # Plain old text button, disabled.
        b = buttons.GenButton(self, -1, 'disabled')
        self.Bind(wx.EVT_BUTTON, self.OnButton, b)
        b.Enable(False)
        sizer.Add(b)

        # This time, we let the botton be as big as it can be.
        # Also, this one is fancier, with custom colors and bezel size.
        b = buttons.GenButton(self, -1, 'bigger')
        self.Bind(wx.EVT_BUTTON, self.OnBiggerButton, b)
        b.SetFont(wx.Font(20, wx.FONTFAMILY_SWISS, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD, False))
        b.SetBezelWidth(5)
        b.SetMinSize(wx.DefaultSize)
        b.SetBackgroundColour("Navy")
        b.SetForegroundColour(wx.WHITE)
        b.SetToolTip("This is a BIG button...")
        # let the sizer set best size
        sizer.Add(b, flag=wx.ADJUST_MINSIZE)

        # An image button
        bmp = images.Test2.GetBitmap()
        b = buttons.GenBitmapButton(self, -1, bmp)
        self.Bind(wx.EVT_BUTTON, self.OnButton, b)
        sizer.Add(b)

        # An image button, disabled.
        bmp = images.Test2.GetBitmap()
        b = buttons.GenBitmapButton(self, -1, bmp)
        self.Bind(wx.EVT_BUTTON, self.OnButton, b)
        sizer.Add(b)
        b.Enable(False)

        # An image button, using a mask to get rid of the
        # undesireable part of the image
        b = buttons.GenBitmapButton(self, -1, None)
        self.Bind(wx.EVT_BUTTON, self.OnButton, b)
        bmp = images.Bulb1.GetBitmap()
        mask = wx.Mask(bmp, wx.BLUE)
        bmp.SetMask(mask)
        b.SetBitmapLabel(bmp)
        bmp = images.Bulb2.GetBitmap()
        mask = wx.Mask(bmp, wx.BLUE)
        bmp.SetMask(mask)
        b.SetBitmapSelected(bmp)
        b.SetInitialSize()
        sizer.Add(b)

        # A toggle button
        b = buttons.GenToggleButton(self, -1, "Toggle Button")
        self.Bind(wx.EVT_BUTTON, self.OnToggleButton, b)
        sizer.Add(b)

        # An image toggle button
        b = buttons.GenBitmapToggleButton(self, -1, None)
        self.Bind(wx.EVT_BUTTON, self.OnToggleButton, b)
        bmp = images.Bulb1.GetBitmap()
        mask = wx.Mask(bmp, wx.BLUE)
        bmp.SetMask(mask)
        b.SetBitmapLabel(bmp)
        bmp = images.Bulb2.GetBitmap()
        mask = wx.Mask(bmp, wx.BLUE)
        bmp.SetMask(mask)
        b.SetBitmapSelected(bmp)
        b.SetToggle(True)
        b.SetInitialSize()
        sizer.Add(b)

        # A bitmap button with text.
        b = buttons.GenBitmapTextButton(self, -1, None, "Bitmapped Text", size = (200, 45))
        self.Bind(wx.EVT_BUTTON, self.OnButton, b)
        bmp = images.Bulb1.GetBitmap()
        mask = wx.Mask(bmp, wx.BLUE)
        bmp.SetMask(mask)
        b.SetBitmapLabel(bmp)
        bmp = images.Bulb2.GetBitmap()
        mask = wx.Mask(bmp, wx.BLUE)
        bmp.SetMask(mask)
        b.SetBitmapSelected(bmp)
        b.SetUseFocusIndicator(False)
        b.SetInitialSize()
        sizer.Add(b)

        # a flat text button
        b = buttons.GenButton(self, -1, 'Flat buttons too!', style=wx.BORDER_NONE)
        self.Bind(wx.EVT_BUTTON, self.OnButton, b)
        sizer.Add(b, flag=wx.ALIGN_CENTER_VERTICAL)

        # A flat image button
        bmp = images.Test2.GetBitmap()
        bmp.SetMaskColour("blue")
        b = buttons.GenBitmapButton(self, -1, bmp, style=wx.BORDER_NONE)
        self.Bind(wx.EVT_BUTTON, self.OnButton, b)
        sizer.Add(b)
        ##b.SetBackgroundColour("sky blue")
        ##b.SetBackgroundColour("pink")

        vbox = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(vbox)

        b = buttons.ThemedGenButton(self, -1, 'Drawn with native renderer')
        self.Bind(wx.EVT_BUTTON, self.OnButton, b)
        vbox.Add(b, 0, wx.ALL, 5)

        b = buttons.ThemedGenToggleButton(self, -1, 'native renderered toggle')
        self.Bind(wx.EVT_BUTTON, self.OnButton, b)
        vbox.Add(b, 0, wx.ALL, 5)

        border = wx.BoxSizer(wx.VERTICAL)
        border.Add(sizer, 0, wx.ALL, 25)
        self.SetSizer(border)

    def OnButton(self, event):
        self.log.WriteText("Button Clicked: %d\n" % event.GetId())

    def OnBiggerButton(self, event):
        self.log.WriteText("Bigger Button Clicked: %d\n" % event.GetId())
        b = event.GetEventObject()
        txt = "big " + b.GetLabel()
        b.SetLabel(txt)
        self.GetSizer().Layout()

    def OnToggleButton(self, event):
        msg = (event.GetIsDown() and "on") or "off"
        self.log.WriteText("Button %d Toggled: %s\n" % (event.GetId(), msg))

#----------------------------------------------------------------------

def runTest(frame, nb, log):
    win = TestPanel(nb, log)
    return win

#----------------------------------------------------------------------

overview = buttons.__doc__

if __name__ == '__main__':
    import sys,os
    import run
    run.main(['', os.path.basename(sys.argv[0])] + sys.argv[1:])