text stringlengths 2 1.04M | meta dict |
|---|---|
using System;
using RestSharp;
using RestSharp.Authenticators;
namespace Pinboard.Helpers
{
/// <summary>
/// Implements the auth_token required for Pinboard authentication
/// </summary>
public class TokenAuthenticator : IAuthenticator
{
private string token;
public TokenAuthenticator(string Token)
{
if (!Token.Contains(":"))
{
throw new ApplicationException("Pinboard tokens need to be in the form of username:token");
}
token = Token;
}
public void Authenticate(IRestClient client, IRestRequest request)
{
request.AddParameter("auth_token", token);
}
}
}
| {
"content_hash": "518b3ebd8a287ec4c6e2ae52ee7ece42",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 107,
"avg_line_length": 27.615384615384617,
"alnum_prop": 0.6016713091922006,
"repo_name": "voltagex/SharpPinboard",
"id": "7bebf3d12c75bfe9a368609e884ae5b17fff24a2",
"size": "720",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Pinboard.Helpers/TokenAuthenticator.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "41534"
}
],
"symlink_target": ""
} |
<?php
_recordWastedTime("Gotcha! ".$dbgErrorCount++);
$yHtml_Header=false;
$yHtml_CSS=false;
$yHtml_Body=false;
$yHtml_Footer=false;
function closeCurrentWindow()
{
echo "<script>window.close();</script>";
}
function redirectOpener($s, $a, $url='')
{
global $u;
if ($url>'') {
if ((substr($url,0,1)=='?') || (substr($url,0,1)=='&'))
$url=substr($url,1);
$urlItems=explode('&',$url);
$url='';
foreach($urlItems as $ui) {
$ui=explode('=', $ui);
$k=$ui[0];
$v=$ui[1];
if (!((strtolower($k)=='s') || (strtolower($k)=='a') || (strtolower($k)=='u'))) {
if ($url>'')
$url.='&';
$url.="$k=$v";
}
}
_dumpY(16,0,"Redirecting opener to '$url'");
}
echo "<script>window.opener.document.location = '?u=$u&s=$s&a=$a&$url';</script>";
}
function _createHTMLHeader_($cssHeaderText)
{
global $yHtml_Header, $appCharset, $cfgAppLang, $appTitle;
if (!$yHtml_Header) {
$yHtml_Header=true;
echo "<!DOCTYPE html>\n";
if ($cfgAppLang>'')
echo "<html lang='$cfgAppLang'>\n";
echo "<head>\n";
echo "<meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1' />\n";
if ($appCharset>'')
echo "<meta charset='$appCharset'>\n";
else {
$serverCharset = setlocale(LC_CTYPE, 0);
if (strpos($serverCharset, '.')>0)
$serverCharset = substr($serverCharset, strpos($serverCharset, '.')+1);
echo "<meta charset='$serverCharset'>\n";
}
$appTitle=trim($appTitle);
if ($appTitle>'') {
echo "<title>$appTitle</title>\n";
}
echo "<meta http-equiv='X-UA-Compatible' content='IE=EmulateIE8' />\n";
echo $cssHeaderText;
/*
echo "\n<!--[if lt IE 9]>\n\t<script src='http://html5shiv.googlecode.com/svn/trunk/html5.js'></script>\n<![endif]-->\n";
//echo "<!-- $appName.$s.$a.$aBody (WoH:$withoutHeader WoB:$withoutBody)-->\n";
echo "<script src=".bestName("yloader.js",1)."></script>\n";
*/
echo "</head>\n";
}
}
global $__API_START_TS;
$__API_START_TS=0;
function registerAPIUsageStart() {
global $s, $a, $__API_START_TS, $cfgApiProfilerEnabled;
if ($cfgApiProfilerEnabled == 'yes') {
if (lock("api-usage-$s-$a", true)) {
_dump("API-USAGE ($s.$a) start");
$__API_START_TS=date('U');
unlock("api-usage-$s-$a");
}
}
}
function registerAPIUsageFinish() {
global $s, $a, $__API_START_TS, $currentDBVersion, $cfgApiProfilerEnabled;
if (($currentDBVersion>=19) && ($cfgApiProfilerEnabled=='yes')) {
if ($__API_START_TS>0) {
if (lock("api-usage-$s-$a")) {
$info=db_sql("select counter, wastedTime, avgTime from is_api_usage where s='$s' and a='$a'", false);
extract($info);
if (!isset($counter)) {
$counter=0;
db_sql("insert into is_api_usage(s,a, disabled, wastedTime, avgTime, counter) values ('$s', '$a', 'N', 0, 0, 0)");
}
$counter++;
$__API_WASTED_TIME = date('U') - $__API_START_TS;
$wastedTime+=$__API_WASTED_TIME;
$avgTime = $wastedTime / $counter;
db_sql("update is_api_usage set counter=$counter, wastedTime=$wastedTime, avgTime=$avgTime where s='$s' and a='$a'");
_dump("API-USAGE ($s.$a) finish");
unlock("api-usage-$s-$a");
}
}
} else {
if ($currentDBVersion<19)
_dump("currentDBVersion need to be 19 at least. You're on '$currentDBVersion'");
}
}
/*
* Load CSS if it is not an CLI application
* Create HTML header
*/
function initOutput()
{
global $appName, $a, $s, $aBody, $withoutBody, $withoutHeader, $isTablet;
$cssHeaderText='';
// echo "<meta http-equiv='Content-Type' content='text/html; charset=iso-8859-1'>\n";
if ($isTablet)
$device='mobile';
else
$device='desktop';
_dumpY(16,1,"device: $device");
// if there is a pre-configure css file, we try to load it
// cfgUniversalCSS is loaded first and ever
// cfgDesktopCSS ou cfgMobileCSS are loaded as the context indicates it
$cssList=array();
if (isset($GLOBALS["cfgUniversalCSS"]))
if (file_exists($GLOBALS['cfgUniversalCSS']))
array_push($cssList, $GLOBALS['cfgUniversalCSS']);
$cfgVar="cfg".ucfirst($device)."CSS";
if (isset($GLOBALS[$cfgVar]))
if (file_exists($GLOBALS[$cfgVar]))
array_push($cssList, $GLOBALS[$cfgVar]);
$cssList=join(',', $cssList);
if ($cssList=='') {
$cwdName = basename(getcwd());
$appBaseName=substr($cwdName,0,strpos($cwdName.'-','-'));
/*
* sequencia original de busca do CSS
$cssNames = array("default", "default-$device",
"../$appName", "../$appName-$device",
"$appName/$appName", "$appName/$appName-$device",
"includes/default", "includes/default-$device",
"includes/$appName", "includes/$appName-$device",
"$appName", "$appName-$device",
"$appBaseName", "$appBaseName-$device",
"$cwdName", "$cwdName-$device");
*/
$cssBaseNames = array ("default", "$appBaseName", "$appName", "$cwdName");
_dumpY(16,0,$_SERVER['HTTP_USER_AGENT']);
foreach($cssBaseNames as $cssBaseName) {
$cssNames = array("$cssBaseName", "$cssBaseName-$device",
"css/$cssBaseName", "css/$cssBaseName-$device",
"$appName/$cssBaseName", "$appName/$cssBaseName-$device",
"includes/$cssBaseName", "includes/$cssBaseName-$device",
"../$cssBaseName", "../$cssBaseName-$device");
foreach($cssNames as $cssName) {
if (file_exists("$cssName.min.css"))
$cssName.='.min.css';
else
$cssName.='.css';
_dumpY(16,4,"is an $cssName ?");
if ( (file_exists($cssName)) &&
(strpos($cssList,$cssName)===FALSE) ) {
if (file_exists('version.inf'))
$version='v='.join('',file('version.inf'));
else
$version=md5(date('U'));
$cssHeaderText.="\n<link href='$cssName?$version' rel='stylesheet' type='text/css'>";
if ($cssList>'')
$cssList.=', ';
$cssList.=$cssName;
}
}
}
}
_dumpY(16,1,"CSS: ($cssList) (Tablet?: $isTablet)");
if ($cssList=='')
_dumpY(16,0,"Without CSS");
_createHTMLHeader_($cssHeaderText);
echo "\n<!-- START OF OUTPUT -->\n";
}
function finishOutput()
{
global $s, $a, $u;
echo "\n<!-- END OF OUTPUT FOR '$s.$a'-->\n";
_dumpY(16,1,"End Output");
}
$__messagesHandler = array();
// this functions transform comma separated parameters and value
// in an associative array
function getQueryParameters($asGlobals=false)
{
_die("OBSOLETO, utilize 'xq_extractValuesFromQuery()' em lugar de 'getQueryParameters()'");
/*
$fieldName=unparentesis($GLOBALS['fieldName']);
$fieldValue=unparentesis($GLOBALS['fieldValue']);
$ret=array();
while ($fieldName>'') {
$aFieldName=getNextValue($fieldName,',');
$aFieldValue=getNextValue($fieldValue,',');
$ret[$aFieldName]=$aFieldValue;
if ($asGlobals)
$GLOBALS[$aFieldName]=$aFieldValue;
}
return $ret;
*/
}
function xq_addToFieldList(&$fieldList, $domainTable, $fieldToBeAdd)
{
$fieldToBeAdd = explode(';',$fieldToBeAdd);
foreach($fieldToBeAdd as $fieldName) {
if (!in_array($fieldName, $fieldList))
if (db_fieldExists($domainTable, $fieldName))
$fieldList[]=$fieldName;
}
}
function xq_getFieldList($domainTable='', $exceptionList='', $prefix='', $posfix='')
{
$exceptionList = explode(';',$exceptionList);
$fieldName = unparentesis($GLOBALS['fieldName']);
$fieldList = explode(",",$fieldName);
$ret=array();
foreach($fieldList as $fieldName) {
$originalFieldName = $fieldName;
$fieldNameCanBeUsed = ($domainTable=='');
if (($prefix>'') && (substr($fieldName,0,strlen($prefix))==$prefix)) {
$fieldName = substr($fieldName, strlen($prefix));
if (!$fieldNameCanBeUsed) {
$fieldNameCanBeUsed = db_fieldExists($domainTable, $fieldName);
if (!$fieldNameCanBeUsed)
$fieldName = lcfirst($fieldName);
}
}
if (($posfix>'') && (substr($fieldName,strlen($fieldName)-strlen($posfix))==$posfix)) {
$fieldName = substr($fieldName, 0, strlen($fieldName)-strlen($posfix));
}
if (!$fieldNameCanBeUsed)
$fieldNameCanBeUsed = db_fieldExists($domainTable, $fieldName);
if ( $fieldNameCanBeUsed ) {
if (!in_array($fieldName, $exceptionList))
$ret[$fieldName] = $GLOBALS[$originalFieldName];
}
}
return $ret;
}
function xq_extractValue(&$ret, $aFieldName, $aFieldValue, $asGlobals, $xq_prefix, $xq_postfix, $xq_only_composed_names=false)
{
// $aFieldValue=urldecode($aFieldValue);
$reserverWords = array('u', 's', 'a', 'fieldName', 'fieldValue');
if (!in_array(strtolower($aFieldName), $reserverWords)) {
_dumpY(16,0,"A: $aFieldName");
if ((strtolower($aFieldValue)=='null') || (strtolower($aFieldValue)=='undefined'))
$aFieldValue=null;
$aFieldValue = str_replace("\!\!", '&', $aFieldValue);
$canUse=!$xq_only_composed_names;
/* discard prefix */
if ($xq_prefix>'') {
if (substr($aFieldName,0,strlen($xq_prefix))==$xq_prefix) {
$canUse=true;
$aFieldName=substr($aFieldName,strlen($xq_prefix));
}
}
/* discard postfix */
if ($xq_postfix>'') {
if (substr($aFieldName, -strlen($xq_postfix))==$xq_postfix) {
$canUse=true;
$aFieldName=substr($aFieldName, 0, strlen($aFieldName)-strlen($xq_postfix));
}
}
if (($canUse) && ($aFieldName>'')) {
if ($aFieldName!='fieldValue')
$aFieldValue=rawurldecode($aFieldValue);
_dumpY(16,0,"B: $aFieldName");
$ret[$aFieldName]=$aFieldValue;
if ($asGlobals)
$GLOBALS[$aFieldName]=$aFieldValue;
}
}
}
function xq_varValue($arrayOfValues, $varName)
{
$ret=null;
if (isset($arrayOfValues[$varName]))
$ret=$arrayOfValues[$varName];
else if (isset($GLOBALS[$varName]))
$ret=$GLOBALS[$varName];
return $ret;
}
global $_REQUEST2;
$_REQUEST2 = array();
function xq_injectValueIntoQuery($k, $v)
{
global $_REQUEST2;
$_REQUEST2[$k] = $v;
}
function xq_extractValuesFromQuery($asGlobals=false, $xq_prefix='', $xq_postfix='', $xq_only_composed_names=false)
{
global $_REQUEST2;
$ret=array();
if (isset($_REQUEST)) {
foreach($_REQUEST as $k=>$v) {
xq_extractValue($ret, $k, $v, $asGlobals, $xq_prefix, $xq_postfix, $xq_only_composed_names);
}
}
foreach($_REQUEST2 as $k=>$v) {
xq_extractValue($ret, $k, $v, $asGlobals, $xq_prefix, $xq_postfix, $xq_only_composed_names);
}
$fieldName = unparentesis(xq_varValue($ret, 'fieldName'));
$fieldValue = unparentesis(xq_varValue($ret, 'fieldValue'));
$fieldValue=str_replace("'", "'", $fieldValue);
$fieldValue=str_replace('"', """, $fieldValue);
while ($fieldName>'') {
$aFieldName=unquote(getNextValue($fieldName,','));
$aFieldValue=unquote(getNextValue($fieldValue,','));
$aFieldValue=str_replace("'", "'", $aFieldValue);
$aFieldValue=str_replace(""", '"', $aFieldValue);
$aFieldValue=escapeString($aFieldValue);
xq_extractValue($ret, $aFieldName, $aFieldValue, $asGlobals, $xq_prefix, $xq_postfix, $xq_only_composed_names);
}
// die('\n\n');
return $ret;
}
function xq_printXML(&$output, $keyName, $keyValue)
{
if (is_array($keyValue)) {
$output.="<$keyName>";
foreach($keyValue as $k => $v)
xq_printXML($output, $k, $v);
$output.="</$keyName>";
} else {
if (strpos($keyName,'/') > 0 ) {
$keyList=explode('/',$keyName);
$k0=$keyList[0];
$openKey='';
$closeKey='';
for($i=0;$i<count($keyList);$i++) {
$k=$keyList[$i];
if (is_numeric($k)) {
$k=$k0.$k."_";
}
$openKey.="<$k>";
$closeKey="</$k>".$closeKey;
}
$output.="$openKey$keyValue$closeKey";
} else {
if (is_numeric($keyName))
$keyName="n$keyName";
$output.="<$keyName>$keyValue</$keyName>\n";
}
}
return $output;
}
global $_xq_context_;
if (!isset($_xq_context_))
$_xq_context_=array();
function xq_context($aIndex, $aValue, $replaceIfExists=true)
{
global $_xq_context_;
if (is_string($aValue)) {
$auxValue=iconv("UTF-8", "iso-8859-1", $aValue);
if (strlen($auxValue)>0) {
if (strlen($auxValue<$aValue))
$aValue=$auxValue;
}
}
// echo "$aValue ".mb_detect_encoding($aValue)." - "."\n";
// mb_encode_numericentity($aValue, array(0x80, 0xff, 0, 0xff), "iso-8859-1")."\n";
if (trim($aIndex)>'') {
if (strpos($aIndex,'/')>0) {
$keyList = explode('/', $aIndex);
$k0=$keyList[0];
if (!isset($_xq_context_[$k0]))
$_xq_context_[$k0] = array();
$aux=&$_xq_context_[$k0];
for($i=1; $i<count($keyList)-1; $i++) {
$k=$keyList[$i];
if (!isset($aux[$k]));
$aux[$k]=array();
$aux=$aux[$k];
}
$itemKey=$keyList[count($keyList)-1];
if (is_numeric($itemKey))
$itemKey="$k0$itemKey";
$aux[$itemKey]=$aValue;
} else {
if ((!is_array($aValue)) && (trim($aValue)=='')) {
if (isset($_xq_context_[$aIndex]))
unset($_xq_context_[$aIndex]);
} else {
if (($replaceIfExists) || (!isset($_xq_context_[$aIndex])))
$_xq_context_[$aIndex]=$aValue;
}
}
}
return $_xq_context_;
}
function xq_produceContext($callBackFunction, $xmlRowsData, $cRegs, $userMsg=null, $firstRow=null, $requestedRows=null, $sqlID='',$progressBarID='', $navigatorID='',$formFile='')
{
global $formID, $targetTableID, $_xq_context_, $lastAction, $lastError, $_requiredFields, $xq_start, $xq_requestedRows;
if ($firstRow == null)
$firstRow = intval($xq_start);
if ($requestedRows == null)
$requestedRows = intval($xq_requestedRows);
xq_context('navScript', $formFile, false);
xq_context('formID', $formID, false);
xq_context('targetTableID', $targetTableID, false);
xq_context('navigatorID', $navigatorID, false);
xq_context('progressBarID', $progressBarID, false);
xq_context('sqlID', $sqlID, false);
xq_context('requestedRows', $requestedRows, false);
xq_context('firstRow', $firstRow, false);
if ($userMsg!=null)
xq_context('userMsg', $userMsg, false);
xq_context('lastAction', $lastAction, false);
xq_context('lastError', explode("\n",$lastError), false);
xq_context('rowCount', intval($cRegs), false);
xq_context('requiredFields', $_requiredFields, false);
while (strpos($userMsg,"\n ")>0)
$userMsg=str_replace("\n ", "\n", $userMsg);
$xmlData =" <callBackFunction>$callBackFunction</callBackFunction>\n";
$xmlData.=" <dataContext>\n";
foreach($_xq_context_ as $k => $v) {
xq_printXML($xmlData, $k, $v);
}
$xmlData.=" </dataContext>\n";
$xmlData.=" <data>\n$xmlRowsData</data>\n";
return $xmlData;
}
/*
* xq_produceReturnLinesFromArray
* xq_produceReturnLinesFromSQL
*
* as duas geram linhas parciais de xml simples para usar com QUERY.PHP
*
* 26/ago/10 - caso precise calcular uma coluna a partir de outra,
* indique calc_nomeFuncao como nome do campo
* e implemente CALC_NOMEFUNCAO() nas suas rotinas
* 29/out/10 - foi acrescentada xq_produceReturnLinesFromArray para gerar resultados
* a partir de um vetor associativo. � usada por xq_produceReturnLinesFromSQL
* 05/jul/11 - foi acrescentada xq_calculatedField para atender os campos CALC_NOMEFUNCAO()
* desde outros comandos db_*. Veja por exemplo db_fetch_array
*/
$uncoveredFunctions=Array();
function xq_calculatedField(&$d, &$k, &$v)
{
global $uncoveredFunctions;
$knum=intval(is_numeric($k));
if (!$knum) {
$funcName=strtoupper($k);
if (substr($funcName,0,5)=='CALC_') {
if (function_exists($k)) {
$v=maskHTML($k($d));
} else {
if (! in_array($funcName, $uncoveredFunctions)) {
array_push($uncoveredFunctions, $funcName);
_dumpY(16,0,"ERROR: function '$funcName()' does not exists in context");
}
}
}
}
return $v;
}
function xq_produceReturnLinesFromInnerArray($d, $colNames=false, $nonEmptyField='', $innerKeySeed='', $xq_prefix='', $xq_postfix='')
{
$ret='';
foreach($d as $k => $v) {
if ("$k"!='__COUNT__') {
if (is_numeric($k)) {
$keyName = $innerKeyNdx.'_'.$k;
} else
$keyName = trim($k);
$keyName="$xq_prefix$keyName$xq_postfix";
if (is_array($v))
$v=xq_produceReturnLinesFromInnerArray($v, $colNames, $nonEmptyField, $keyName, $xq_prefix, $xq_postfix);
$ret.="<$keyName>$v</$keyName>";
}
}
return $ret;
}
function xq_produceReturnLinesFromArray($d, &$cRegs, $colNames=false, $nonEmptyField='', $xq_prefix='', $xq_postfix='')
{
global $xq_return_array;
$auxRow='';
$col=0;
$xmlRow="";
$mandatoryFieldFilled=($nonEmptyField=='');
$allAreNumricKeys=true;
foreach($d as $k=>$v)
if (!is_numeric($k))
$allAreNumricKeys=false;
if ($allAreNumricKeys) {
$cRegs=intval($cRegs);
foreach($d as $k=>$v) {
if (is_array($v)) {
$v=xq_produceReturnLinesFromInnerArray($v, $colNames, $nonEmptyField, '_'.$k, $xq_prefix, $xq_postfix);
} else
$v=maskHTML(trim($v));
$xmlRow.=" <row rowid='$cRegs'>\n";
$xmlRow.=" <rowid>$cRegs</rowid>\n";
$xmlRow.=" <data>$v</data>";
$xmlRow.=" </row>\n";
$cRegs++;
}
} else {
$colNames=intval($colNames);
$CIKeys=array();
foreach($d as $k=>$v) {
if ("$k"!="__COUNT__") {
$CIK=strtolower($k);
if (( db_status(_DB_CONNECTED_)==0 ) ||
(db_connectionTypeIs(_MYSQL_)) ||
(db_connectionTypeIs(_MYSQLI_)) ||
(!in_array($CIK, $CIKeys))) {
$CIKeys[]=$CIK;
$knum = is_numeric($k);
$itemKeyRequired = is_array($v);
if ($itemKeyRequired) {
$v=xq_produceReturnLinesFromInnerArray($v, $colNames, $nonEmptyField, '_'.$k, $xq_prefix, $xq_postfix);
} else
$v=maskHTML(trim($v));
$canAdd=false;
$v=mb_convert_encoding($v, "iso-8859-1", mb_detect_encoding($v));
// $v=xq_calculatedField($d, $k, $v);
_dumpY(16,3,"$k => $v");
$fieldAttrib='';
if ($colNames)
$canAdd=!$knum;
else {
$canAdd=true;
if ($canAdd) {
$k="data";
$col++;
$fieldAttrib=" col='$col'";
}
}
$k="$xq_prefix$k$xq_postfix";
if ($canAdd) {
if ($itemKeyRequired) {
$auxRow.=" <rowItem id='$k'$fieldAttrib>$v</rowItem>\n";
} else {
$auxRow.=" <$k$fieldAttrib>$v</$k>\n";
}
if ($k==$nonEmptyField) {
$mandatoryFieldFilled=(trim($v)>'');
}
}
}
}
}
if ($mandatoryFieldFilled) {
$cRegs=intval($cRegs);
$xmlRow =" <row rowid='$cRegs'>\n";
$xmlRow.=" <rowid>$cRegs</rowid>\n";
$xmlRow.="$auxRow";
$xmlRow.=" </row>\n";
$cRegs++;
} else {
$xmlRow='';
}
}
return $xmlRow;
}
/* xq_produceReturnLinesFromSQL
* recebe um comando SQL
* devolve um xml parcial contendo as colunas indicadas no XML
*/
function xq_produceReturnLinesFromSQL($sql, &$cRegs, $colNames=false, $maxRecordCount=-1, $nonEmptyField='', $xq_prefix='', $xq_postfix='')
{
global $uncoveredFunctions, $userMsg;
$xmlRows='';
$sql=html_entity_decode(unquote($sql));
$q=db_query($sql);
while ($d=db_fetch_array($q,false)) {
if (!$colNames)
$d=array_unique($d);
$xmlRows.=xq_produceReturnLinesFromArray($d, $cRegs, $colNames, $nonEmptyField, $xq_prefix, $xq_postfix);
if (($maxRecordCount>0) && ($cRegs>=$maxRecordCount)) {
$userMsg="Limite de busca atingido. Seja mais especifico";
_dump($userMsg);
break;
}
}
return $xmlRows;
}
function xq_produceReturnLines($returnSet, $xq_usingColNames, $xq_countLimit, $xq_prefix='', $xq_postfix='')
{
global $xq_return, $xq_regCount, $xq_requestedRows;
$xq_requestedRows = $xq_countLimit;
if (is_array($returnSet)) {
$isArrayOfArray=false;
foreach($returnSet as $k=>$v)
if (is_array($v))
$isArrayOfArray=true;
if ($isArrayOfArray) {
$xq_return='';
foreach($returnSet as $k=>$v) {
$auxRet = xq_produceReturnLinesFromArray($v, $xq_regCount, $xq_usingColNames, '', $xq_prefix, $xq_postfix);
$xq_return.=$auxRet;
}
} else
$xq_return = xq_produceReturnLinesFromArray($returnSet, $xq_regCount, $xq_usingColNames, '', $xq_prefix, $xq_postfix);
} else {
if ($returnSet>'')
$xq_return=xq_produceReturnLinesFromSQL($returnSet, $xq_regCount, $xq_usingColNames, $xq_countLimit, '', $xq_prefix, $xq_postfix);
}
return $xq_return;
}
function jr_produceReturnLines($returnSet) {
if (is_string($returnSet)) {
$auxSet=$returnSet;
$auxSet=strtolower(getNextValue($auxSet,' '));
if (($auxSet=="select") || ($auxSet=="insert") || ($auxSet=="delete") || ($auxSet=="update") || ($auxSet=="replace")) {
$auxSet=db_queryAndFillArray($returnSet);
$returnSet=array();
foreach($auxSet as $d) {
$auxLine=array();
foreach($d as $k=>$v) {
$canUse=true;
if (db_connectionTypeIs(_FIREBIRD_))
$canUse=(strtoupper($k)==$k);
if ($canUse)
if ($k!="__COUNT__")
$auxLine[$k]=$v;
}
$returnSet[count($returnSet)] = $auxLine;
}
}
}
$ret = json_encode($returnSet);
// $ret = str_replace(",\"", ",\n\"", $ret);
return $ret;
}
/* functions to verify form content */
function strFilled($str)
{
return strlen(trim($str))>0;
}
function validEmail($email)
{
return filter_var($email, FILTER_VALIDATE_EMAIL);
}
global $_xq_formErrorSequence_;
$_xq_formErrorSequence_=0;
function setFieldError($msg, $varName='')
{
global $_xq_formErrorSequence_;
_requiredField($varName);
$_xq_formErrorSequence_++;
_recordError("$_xq_formErrorSequence_) $msg");
xq_context("formError/$varName", $msg);
}
function verifyFormValue($varName, $func, $msg, $setAsFormError=true)
{
$ret=true;
$functions=explode(';',$func);
foreach($functions as $func) {
if ($ret) {
if (function_exists($func)) {
if ($func($GLOBALS[$varName])==false) {
if ($setAsFormError)
setFieldError($msg, $varName);
else {
_requiredField($varName);
_recordError($msg,0);
}
$ret=false;
}
} else
_die("'$func' was not found as global function");
}
}
return $ret;
}
/*
* Functions to be used with Javascript Inter User Messages in
* the context of YeAPF applications
*
*/
function qy_msgProc($aSourceUserId, $aMessage, $aWParam, $aLParam)
{
global $sysTimeStamp, $__messagesHandler;
$ret=array();
if ($aMessage=='') {
$ret['sourceUserId']=$aSourceUserId;
$ret['message']='systemTick';
$ret['wParam']=$sysTimeStamp;
$ret['lParam']=0;
} else {
$ret['sourceUserId']=$aSourceUserId;
$ret['message']=$aMessage;
$ret['wParam']=$aWParam;
$ret['lParam']=$aLParam;
foreach($__messagesHandler as $mh)
if (function_exists($mh))
$ret=$mh($aSourceUserId, $aMessage, $aWParam, $aLParam);
}
return $ret;
}
function qy_msg($a)
{
global $sysTimeStamp,
$userContext,
$u, $formID, $messagePeekerInterval,
$xq_return, $xq_regCount,
$targetUser, $message, $wParam, $lParam, $broadcastCondition;
if (!is_object($userContext)) {
$aux=debug_backtrace();
foreach($aux as $k=>$v) {
foreach($v as $k1 => $v1) {
echo "$k $k1 ";
if ($k1=='args') {
echo "(";
foreach($v1 as $k2 => $v2) {
if ($k2>0)
echo ',';
echo "'$v2'";
}
echo ")\n";
} else
echo " $v1";
echo "\n";
}
}
die("userContext not initialized");
}
$xq_regCount=0;
$xq_return='';
/*
* $formID vazio indica primeira solicita��o de lista
* de mensagens sendo requirida pelo cliente yeapf.js
*/
if ($formID=='') {
$formID=md5('ym'.y_uniqid());
$userContext->RegisterFormID($messagePeekerInterval);
}
//$messages=xq_produceReturnLinesFromArray($xq_return_array,$xq_regCount,true);
// messages vindos do pr�prio usu�rio tem prioridade sobre os enviados pelo resto
// ent�o eles n�o entram no processamento natural da pilha
if ( ($a=='peekMessage') || ($targetUser==$u) ) {
$messageList = $userContext->PeekMessages();
$aSourceUserID=$u;
$aMessage=$message;
$aWParam=$wParam;
$aLParam=$lParam;
do {
_dumpY(16,0,"@ sending $aSourceUserID, $aMessage, $aWParam, $aLParam");
$xq_return_array = qy_msgProc($aSourceUserID, $aMessage, $aWParam, $aLParam);
if (count($xq_return_array)>0)
$xq_return.=xq_produceReturnLinesFromArray($xq_return_array, $xq_regCount, true, '', $xq_prefix, $xq_postfix);
$moreFeed=false;
$msg=array_shift($messageList);
if ($msg>'') {
$aSourceUserID=getNextValue($msg,';');
$aMessage=getNextValue($msg,';');
$aWParam=getNextValue($msg,';');
$aLParam=getNextValue($msg,';');
$moreFeed=($aMessage>'');
}
} while ($moreFeed);
} else if ($a=='postMessage') {
if ($targetUser=='*') {
$aux=unquote($broadcastCondition);
$varName=getNextValue($aux,'=');
$varValue=getNextValue($aux,'=');
$userContext->BroadcastMessage($varName, $varValue, $message, $wParam, $lParam);
} else
$userContext->PostMessage($targetUser, $message, $wParam, $lParam);
}
}
function addMessageHandler($mh)
{
global $__messagesHandler;
if ($mh!='qy_msgProc')
if (!in_array($mh,$__messagesHandler)) {
_dumpY(16,0,"registering '$mh' as message handler");
array_push($__messagesHandler,$mh);
}
}
function produceRestOutput($jsonData)
{
global $callback, $callbackId, $scriptSequence, $userMsg, $_xq_context_, $ts;
if ((!isset($callbackId)) || ($callbackId==''))
$callbackId = 'null';
if ((!isset($scriptSequence)) || ($scriptSequence==''))
$scriptSequence = '0';
if ((!isset($callback)) || ($callback==''))
$callback='ycomm.dummy';
$_xq_context_['callback']=$callbackId;
$_xq_context_['scriptSequence']=$scriptSequence;
$context=json_encode($_xq_context_);
$returnAsScript=false;
/* 0.9.0 */
if (isset($GLOBALS['_rap_'.$ts])) {
if ($GLOBALS['_rap_'.$ts]==1)
$returnAsScript=true;
}
if (isset($GLOBALS['fieldName']) && isset($GLOBALS['fieldValue']) && isset($GLOBALS['ts']))
$returnAsScript=true;
if ($returnAsScript) {
$script=
"if (typeof $callback == 'function') {
$callback(200, 0, $jsonData, '$userMsg', $context);
} else
console.warn(\"'$callback' callback function was not found\");
";
} else {
$script = $jsonData;
}
return $script;
}
function qyeapf($a) {
extract(xq_extractValuesFromQuery());
$ret="";
if ($a=='ping') {
$ret['serverTime'] = date('U');
$ret['timezone'] = date('Z');
$ret['ip'] = getCurrentIp();
$ret['pingCount'] = intval($pingCount)+1;
} else if ($a=='serverTime') {
$ret['serverTime'] = date('Y-m-d H:i:s');
} else if ($a=='nodeKeepAlive') {
$ret=yNode::nodeKeepAlive();
} else if($a=='nodeCheckSeq') {
$r=yNode::requestNodeSequenceVerification();
if ($r==-1) {
$ret['result']='NotTested';
} else {
$ret['result']=$r?'true':'false';
}
}
xq_produceReturnLines($ret, true, $countLimit);
}
function ryeapf($a) {
global $callback, $cfgMainFolder, $cfgNodePrefix, $cfgClientConfig, $server_IP;
extract(xq_extractValuesFromQuery());
$ret=array();
if ($a=='ping') {
$ret['serverTime'] = date('U');
$ret['timezone'] = date('Z');
$ret['ip'] = getCurrentIp();
$ret['pingCount'] = intval($pingCount)+1;
} else if ($a=='serverTime') {
$ret['serverTime'] = date('Y-m-d H:i:s');
} else if ($a=='nodeKeepAlive') {
$ret=yNode::nodeKeepAlive();
} else if($a=='nodeCheckSeq') {
$r=yNode::requestNodeSequenceVerification();
if ($r==-1) {
$ret['result']='NotTested';
} else {
$ret['result']=$r?'true':'false';
}
}
$jsonRet = json_encode($ret);
echo produceRestOutput($jsonRet);
}
function yeapfAppEvents(&$s, $a)
{
global $userContext, $withoutHeader, $aBody,
$withoutHeader, $currentSubject ;
if ($s=='yeapf') {
switch($a) {
case 'getAppHeader':
$withoutHeader=true;
$aBody='e_app_header.html';
break;
case 'getMainBody':
case 'buildMainBody':
$withoutHeader=true;
$aBody='e_main_body.html';
break;
case 'getAppFooter':
$withoutHeader=true;
$aBody='e_footer_body.html';
break;
case 'logoff':
case 'exit':
$userContext->logoff();
$withoutHeader=true;
$aBody='f_logoff.html';
break;
default:
if (isset($userContext)) {
if ($s=='') {
$userContext->loadUserVars('currentSubject');
$s=$currentSubject;
} else {
if ($s!='yeapf') {
$currentSubject=$s;
$userContext->addUserVars('currentSubject');
}
}
}
break;
}
}
}
addEventHandler('yeapfAppEvents');
_recordWastedTime("yeapf.application.php Carregado");
?>
| {
"content_hash": "068c2805d1da53577044266e493e8ad9",
"timestamp": "",
"source": "github",
"line_count": 1054,
"max_line_length": 180,
"avg_line_length": 30.056925996204935,
"alnum_prop": 0.5392992424242424,
"repo_name": "EDortta/YeAPF",
"id": "323ca5ec0a8d8f22c9575c53d8e0e3dd8edd5165",
"size": "31892",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "0.8.60/includes/yeapf.application.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1434759"
},
{
"name": "HTML",
"bytes": "9865143"
},
{
"name": "JavaScript",
"bytes": "43628308"
},
{
"name": "PHP",
"bytes": "32252830"
},
{
"name": "Shell",
"bytes": "216948"
}
],
"symlink_target": ""
} |
package scheduler
import (
"fmt"
"time"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/apimachinery/pkg/util/sets"
utilfeature "k8s.io/apiserver/pkg/util/feature"
"k8s.io/client-go/informers"
coreinformers "k8s.io/client-go/informers/core/v1"
clientset "k8s.io/client-go/kubernetes"
corelisters "k8s.io/client-go/listers/core/v1"
policylisters "k8s.io/client-go/listers/policy/v1beta1"
storagelisters "k8s.io/client-go/listers/storage/v1"
"k8s.io/client-go/tools/cache"
"k8s.io/klog"
kubefeatures "k8s.io/kubernetes/pkg/features"
"k8s.io/kubernetes/pkg/scheduler/algorithm"
"k8s.io/kubernetes/pkg/scheduler/algorithm/predicates"
"k8s.io/kubernetes/pkg/scheduler/algorithm/priorities"
schedulerapi "k8s.io/kubernetes/pkg/scheduler/apis/config"
"k8s.io/kubernetes/pkg/scheduler/apis/config/validation"
"k8s.io/kubernetes/pkg/scheduler/core"
"k8s.io/kubernetes/pkg/scheduler/framework/plugins"
framework "k8s.io/kubernetes/pkg/scheduler/framework/v1alpha1"
internalcache "k8s.io/kubernetes/pkg/scheduler/internal/cache"
cachedebugger "k8s.io/kubernetes/pkg/scheduler/internal/cache/debugger"
internalqueue "k8s.io/kubernetes/pkg/scheduler/internal/queue"
nodeinfosnapshot "k8s.io/kubernetes/pkg/scheduler/nodeinfo/snapshot"
"k8s.io/kubernetes/pkg/scheduler/volumebinder"
)
const (
initialGetBackoff = 100 * time.Millisecond
maximalGetBackoff = time.Minute
)
// Binder knows how to write a binding.
type Binder interface {
Bind(binding *v1.Binding) error
}
// Configurator defines I/O, caching, and other functionality needed to
// construct a new scheduler.
type Configurator struct {
client clientset.Interface
informerFactory informers.SharedInformerFactory
podInformer coreinformers.PodInformer
// Close this to stop all reflectors
StopEverything <-chan struct{}
schedulerCache internalcache.Cache
// RequiredDuringScheduling affinity is not symmetric, but there is an implicit PreferredDuringScheduling affinity rule
// corresponding to every RequiredDuringScheduling affinity rule.
// HardPodAffinitySymmetricWeight represents the weight of implicit PreferredDuringScheduling affinity rule, in the range [0-100].
hardPodAffinitySymmetricWeight int32
// Handles volume binding decisions
volumeBinder *volumebinder.VolumeBinder
// Always check all predicates even if the middle of one predicate fails.
alwaysCheckAllPredicates bool
// Disable pod preemption or not.
disablePreemption bool
// percentageOfNodesToScore specifies percentage of all nodes to score in each scheduling cycle.
percentageOfNodesToScore int32
bindTimeoutSeconds int64
podInitialBackoffSeconds int64
podMaxBackoffSeconds int64
enableNonPreempting bool
// framework configuration arguments.
registry framework.Registry
plugins *schedulerapi.Plugins
pluginConfig []schedulerapi.PluginConfig
pluginConfigProducerRegistry *plugins.ConfigProducerRegistry
nodeInfoSnapshot *nodeinfosnapshot.Snapshot
algorithmFactoryArgs AlgorithmFactoryArgs
configProducerArgs *plugins.ConfigProducerArgs
}
// GetHardPodAffinitySymmetricWeight is exposed for testing.
func (c *Configurator) GetHardPodAffinitySymmetricWeight() int32 {
return c.hardPodAffinitySymmetricWeight
}
// Create creates a scheduler with the default algorithm provider.
func (c *Configurator) Create() (*Scheduler, error) {
return c.CreateFromProvider(DefaultProvider)
}
// CreateFromProvider creates a scheduler from the name of a registered algorithm provider.
func (c *Configurator) CreateFromProvider(providerName string) (*Scheduler, error) {
klog.V(2).Infof("Creating scheduler from algorithm provider '%v'", providerName)
provider, err := GetAlgorithmProvider(providerName)
if err != nil {
return nil, err
}
return c.CreateFromKeys(provider.FitPredicateKeys, provider.PriorityFunctionKeys, []algorithm.SchedulerExtender{})
}
// CreateFromConfig creates a scheduler from the configuration file
func (c *Configurator) CreateFromConfig(policy schedulerapi.Policy) (*Scheduler, error) {
klog.V(2).Infof("Creating scheduler from configuration: %v", policy)
// validate the policy configuration
if err := validation.ValidatePolicy(policy); err != nil {
return nil, err
}
predicateKeys := sets.NewString()
if policy.Predicates == nil {
klog.V(2).Infof("Using predicates from algorithm provider '%v'", DefaultProvider)
provider, err := GetAlgorithmProvider(DefaultProvider)
if err != nil {
return nil, err
}
predicateKeys = provider.FitPredicateKeys
} else {
for _, predicate := range policy.Predicates {
klog.V(2).Infof("Registering predicate: %s", predicate.Name)
predicateKeys.Insert(RegisterCustomFitPredicate(predicate, c.configProducerArgs))
}
}
priorityKeys := sets.NewString()
if policy.Priorities == nil {
klog.V(2).Infof("Using priorities from algorithm provider '%v'", DefaultProvider)
provider, err := GetAlgorithmProvider(DefaultProvider)
if err != nil {
return nil, err
}
priorityKeys = provider.PriorityFunctionKeys
} else {
for _, priority := range policy.Priorities {
if priority.Name == priorities.EqualPriority {
klog.V(2).Infof("Skip registering priority: %s", priority.Name)
continue
}
klog.V(2).Infof("Registering priority: %s", priority.Name)
priorityKeys.Insert(RegisterCustomPriorityFunction(priority, c.configProducerArgs))
}
}
var extenders []algorithm.SchedulerExtender
if len(policy.Extenders) != 0 {
ignoredExtendedResources := sets.NewString()
var ignorableExtenders []algorithm.SchedulerExtender
for ii := range policy.Extenders {
klog.V(2).Infof("Creating extender with config %+v", policy.Extenders[ii])
extender, err := core.NewHTTPExtender(&policy.Extenders[ii])
if err != nil {
return nil, err
}
if !extender.IsIgnorable() {
extenders = append(extenders, extender)
} else {
ignorableExtenders = append(ignorableExtenders, extender)
}
for _, r := range policy.Extenders[ii].ManagedResources {
if r.IgnoredByScheduler {
ignoredExtendedResources.Insert(string(r.Name))
}
}
}
// place ignorable extenders to the tail of extenders
extenders = append(extenders, ignorableExtenders...)
predicates.RegisterPredicateMetadataProducerWithExtendedResourceOptions(ignoredExtendedResources)
}
// Providing HardPodAffinitySymmetricWeight in the policy config is the new and preferred way of providing the value.
// Give it higher precedence than scheduler CLI configuration when it is provided.
if policy.HardPodAffinitySymmetricWeight != 0 {
c.hardPodAffinitySymmetricWeight = policy.HardPodAffinitySymmetricWeight
}
// When AlwaysCheckAllPredicates is set to true, scheduler checks all the configured
// predicates even after one or more of them fails.
if policy.AlwaysCheckAllPredicates {
c.alwaysCheckAllPredicates = policy.AlwaysCheckAllPredicates
}
return c.CreateFromKeys(predicateKeys, priorityKeys, extenders)
}
// CreateFromKeys creates a scheduler from a set of registered fit predicate keys and priority keys.
func (c *Configurator) CreateFromKeys(predicateKeys, priorityKeys sets.String, extenders []algorithm.SchedulerExtender) (*Scheduler, error) {
klog.V(2).Infof("Creating scheduler with fit predicates '%v' and priority functions '%v'", predicateKeys, priorityKeys)
if c.GetHardPodAffinitySymmetricWeight() < 1 || c.GetHardPodAffinitySymmetricWeight() > 100 {
return nil, fmt.Errorf("invalid hardPodAffinitySymmetricWeight: %d, must be in the range 1-100", c.GetHardPodAffinitySymmetricWeight())
}
predicateFuncs, pluginsForPredicates, pluginConfigForPredicates, err := c.getPredicateConfigs(predicateKeys)
if err != nil {
return nil, err
}
priorityConfigs, pluginsForPriorities, pluginConfigForPriorities, err := c.getPriorityConfigs(priorityKeys)
if err != nil {
return nil, err
}
priorityMetaProducer, err := getPriorityMetadataProducer(c.algorithmFactoryArgs)
if err != nil {
return nil, err
}
predicateMetaProducer, err := getPredicateMetadataProducer(c.algorithmFactoryArgs)
if err != nil {
return nil, err
}
// Combine all framework configurations. If this results in any duplication, framework
// instantiation should fail.
var plugins schedulerapi.Plugins
plugins.Append(pluginsForPredicates)
plugins.Append(pluginsForPriorities)
plugins.Append(c.plugins)
var pluginConfig []schedulerapi.PluginConfig
pluginConfig = append(pluginConfig, pluginConfigForPredicates...)
pluginConfig = append(pluginConfig, pluginConfigForPriorities...)
pluginConfig = append(pluginConfig, c.pluginConfig...)
framework, err := framework.NewFramework(
c.registry,
&plugins,
pluginConfig,
framework.WithClientSet(c.client),
framework.WithInformerFactory(c.informerFactory),
framework.WithSnapshotSharedLister(c.nodeInfoSnapshot),
)
if err != nil {
klog.Fatalf("error initializing the scheduling framework: %v", err)
}
podQueue := internalqueue.NewSchedulingQueue(
c.StopEverything,
framework,
internalqueue.WithPodInitialBackoffDuration(time.Duration(c.podInitialBackoffSeconds)*time.Second),
internalqueue.WithPodMaxBackoffDuration(time.Duration(c.podMaxBackoffSeconds)*time.Second),
)
// Setup cache debugger.
debugger := cachedebugger.New(
c.informerFactory.Core().V1().Nodes().Lister(),
c.podInformer.Lister(),
c.schedulerCache,
podQueue,
)
debugger.ListenForSignal(c.StopEverything)
go func() {
<-c.StopEverything
podQueue.Close()
}()
algo := core.NewGenericScheduler(
c.schedulerCache,
podQueue,
predicateFuncs,
predicateMetaProducer,
priorityConfigs,
priorityMetaProducer,
c.nodeInfoSnapshot,
framework,
extenders,
c.volumeBinder,
c.informerFactory.Core().V1().PersistentVolumeClaims().Lister(),
GetPodDisruptionBudgetLister(c.informerFactory),
c.alwaysCheckAllPredicates,
c.disablePreemption,
c.percentageOfNodesToScore,
c.enableNonPreempting,
)
return &Scheduler{
SchedulerCache: c.schedulerCache,
Algorithm: algo,
GetBinder: getBinderFunc(c.client, extenders),
Framework: framework,
NextPod: internalqueue.MakeNextPodFunc(podQueue),
Error: MakeDefaultErrorFunc(c.client, podQueue, c.schedulerCache),
StopEverything: c.StopEverything,
VolumeBinder: c.volumeBinder,
SchedulingQueue: podQueue,
Plugins: plugins,
PluginConfig: pluginConfig,
}, nil
}
// getBinderFunc returns a func which returns an extender that supports bind or a default binder based on the given pod.
func getBinderFunc(client clientset.Interface, extenders []algorithm.SchedulerExtender) func(pod *v1.Pod) Binder {
defaultBinder := &binder{client}
return func(pod *v1.Pod) Binder {
for _, extender := range extenders {
if extender.IsBinder() && extender.IsInterested(pod) {
return extender
}
}
return defaultBinder
}
}
// getPriorityConfigs returns priorities configuration: ones that will run as priorities and ones that will run
// as framework plugins. Specifically, a priority will run as a framework plugin if a plugin config producer was
// registered for that priority.
func (c *Configurator) getPriorityConfigs(priorityKeys sets.String) ([]priorities.PriorityConfig, *schedulerapi.Plugins, []schedulerapi.PluginConfig, error) {
allPriorityConfigs, err := getPriorityFunctionConfigs(priorityKeys, c.algorithmFactoryArgs)
if err != nil {
return nil, nil, nil, err
}
if c.pluginConfigProducerRegistry == nil {
return allPriorityConfigs, nil, nil, nil
}
var priorityConfigs []priorities.PriorityConfig
var plugins schedulerapi.Plugins
var pluginConfig []schedulerapi.PluginConfig
frameworkConfigProducers := c.pluginConfigProducerRegistry.PriorityToConfigProducer
for _, p := range allPriorityConfigs {
if producer, exist := frameworkConfigProducers[p.Name]; exist {
args := *c.configProducerArgs
args.Weight = int32(p.Weight)
pl, pc := producer(args)
plugins.Append(&pl)
pluginConfig = append(pluginConfig, pc...)
} else {
priorityConfigs = append(priorityConfigs, p)
}
}
return priorityConfigs, &plugins, pluginConfig, nil
}
// getPredicateConfigs returns predicates configuration: ones that will run as fitPredicates and ones that will run
// as framework plugins. Specifically, a predicate will run as a framework plugin if a plugin config producer was
// registered for that predicate.
// Note that the framework executes plugins according to their order in the Plugins list, and so predicates run as plugins
// are added to the Plugins list according to the order specified in predicates.Ordering().
func (c *Configurator) getPredicateConfigs(predicateKeys sets.String) (map[string]predicates.FitPredicate, *schedulerapi.Plugins, []schedulerapi.PluginConfig, error) {
allFitPredicates, err := getFitPredicateFunctions(predicateKeys, c.algorithmFactoryArgs)
if err != nil {
return nil, nil, nil, err
}
if c.pluginConfigProducerRegistry == nil {
return allFitPredicates, nil, nil, nil
}
asPlugins := sets.NewString()
asFitPredicates := make(map[string]predicates.FitPredicate)
frameworkConfigProducers := c.pluginConfigProducerRegistry.PredicateToConfigProducer
// First, identify the predicates that will run as actual fit predicates, and ones
// that will run as framework plugins.
for predicateKey := range allFitPredicates {
if _, exist := frameworkConfigProducers[predicateKey]; exist {
asPlugins.Insert(predicateKey)
} else {
asFitPredicates[predicateKey] = allFitPredicates[predicateKey]
}
}
// Second, create the framework plugin configurations, and place them in the order
// that the corresponding predicates were supposed to run.
var plugins schedulerapi.Plugins
var pluginConfig []schedulerapi.PluginConfig
for _, predicateKey := range predicates.Ordering() {
if asPlugins.Has(predicateKey) {
producer := frameworkConfigProducers[predicateKey]
p, pc := producer(*c.configProducerArgs)
plugins.Append(&p)
pluginConfig = append(pluginConfig, pc...)
asPlugins.Delete(predicateKey)
}
}
// Third, add the rest in no specific order.
for predicateKey := range asPlugins {
producer := frameworkConfigProducers[predicateKey]
p, pc := producer(*c.configProducerArgs)
plugins.Append(&p)
pluginConfig = append(pluginConfig, pc...)
}
return asFitPredicates, &plugins, pluginConfig, nil
}
type podInformer struct {
informer cache.SharedIndexInformer
}
func (i *podInformer) Informer() cache.SharedIndexInformer {
return i.informer
}
func (i *podInformer) Lister() corelisters.PodLister {
return corelisters.NewPodLister(i.informer.GetIndexer())
}
// NewPodInformer creates a shared index informer that returns only non-terminal pods.
func NewPodInformer(client clientset.Interface, resyncPeriod time.Duration) coreinformers.PodInformer {
selector := fields.ParseSelectorOrDie(
"status.phase!=" + string(v1.PodSucceeded) +
",status.phase!=" + string(v1.PodFailed))
lw := cache.NewListWatchFromClient(client.CoreV1().RESTClient(), string(v1.ResourcePods), metav1.NamespaceAll, selector)
return &podInformer{
informer: cache.NewSharedIndexInformer(lw, &v1.Pod{}, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}),
}
}
// MakeDefaultErrorFunc construct a function to handle pod scheduler error
func MakeDefaultErrorFunc(client clientset.Interface, podQueue internalqueue.SchedulingQueue, schedulerCache internalcache.Cache) func(*framework.PodInfo, error) {
return func(podInfo *framework.PodInfo, err error) {
pod := podInfo.Pod
if err == core.ErrNoNodesAvailable {
klog.V(2).Infof("Unable to schedule %v/%v: no nodes are registered to the cluster; waiting", pod.Namespace, pod.Name)
} else {
if _, ok := err.(*core.FitError); ok {
klog.V(2).Infof("Unable to schedule %v/%v: no fit: %v; waiting", pod.Namespace, pod.Name, err)
} else if errors.IsNotFound(err) {
klog.V(2).Infof("Unable to schedule %v/%v: possibly due to node not found: %v; waiting", pod.Namespace, pod.Name, err)
if errStatus, ok := err.(errors.APIStatus); ok && errStatus.Status().Details.Kind == "node" {
nodeName := errStatus.Status().Details.Name
// when node is not found, We do not remove the node right away. Trying again to get
// the node and if the node is still not found, then remove it from the scheduler cache.
_, err := client.CoreV1().Nodes().Get(nodeName, metav1.GetOptions{})
if err != nil && errors.IsNotFound(err) {
node := v1.Node{ObjectMeta: metav1.ObjectMeta{Name: nodeName}}
if err := schedulerCache.RemoveNode(&node); err != nil {
klog.V(4).Infof("Node %q is not found; failed to remove it from the cache.", node.Name)
}
}
}
} else {
klog.Errorf("Error scheduling %v/%v: %v; retrying", pod.Namespace, pod.Name, err)
}
}
podSchedulingCycle := podQueue.SchedulingCycle()
// Retry asynchronously.
// Note that this is extremely rudimentary and we need a more real error handling path.
go func() {
defer runtime.HandleCrash()
podID := types.NamespacedName{
Namespace: pod.Namespace,
Name: pod.Name,
}
// An unschedulable pod will be placed in the unschedulable queue.
// This ensures that if the pod is nominated to run on a node,
// scheduler takes the pod into account when running predicates for the node.
// Get the pod again; it may have changed/been scheduled already.
getBackoff := initialGetBackoff
for {
pod, err := client.CoreV1().Pods(podID.Namespace).Get(podID.Name, metav1.GetOptions{})
if err == nil {
if len(pod.Spec.NodeName) == 0 {
podInfo.Pod = pod
if err := podQueue.AddUnschedulableIfNotPresent(podInfo, podSchedulingCycle); err != nil {
klog.Error(err)
}
}
break
}
if errors.IsNotFound(err) {
klog.Warningf("A pod %v no longer exists", podID)
return
}
klog.Errorf("Error getting pod %v for retry: %v; retrying...", podID, err)
if getBackoff = getBackoff * 2; getBackoff > maximalGetBackoff {
getBackoff = maximalGetBackoff
}
time.Sleep(getBackoff)
}
}()
}
}
type binder struct {
Client clientset.Interface
}
// Bind just does a POST binding RPC.
func (b *binder) Bind(binding *v1.Binding) error {
klog.V(3).Infof("Attempting to bind %v to %v", binding.Name, binding.Target.Name)
return b.Client.CoreV1().Pods(binding.Namespace).Bind(binding)
}
// GetPodDisruptionBudgetLister returns pdb lister from the given informer factory. Returns nil if PodDisruptionBudget feature is disabled.
func GetPodDisruptionBudgetLister(informerFactory informers.SharedInformerFactory) policylisters.PodDisruptionBudgetLister {
if utilfeature.DefaultFeatureGate.Enabled(kubefeatures.PodDisruptionBudget) {
return informerFactory.Policy().V1beta1().PodDisruptionBudgets().Lister()
}
return nil
}
// GetCSINodeLister returns CSINode lister from the given informer factory. Returns nil if CSINodeInfo feature is disabled.
func GetCSINodeLister(informerFactory informers.SharedInformerFactory) storagelisters.CSINodeLister {
if utilfeature.DefaultFeatureGate.Enabled(kubefeatures.CSINodeInfo) {
return informerFactory.Storage().V1().CSINodes().Lister()
}
return nil
}
| {
"content_hash": "199425616930b28995d4ed3521f3f67d",
"timestamp": "",
"source": "github",
"line_count": 523,
"max_line_length": 167,
"avg_line_length": 37.17590822179732,
"alnum_prop": 0.7570333796224863,
"repo_name": "ingvagabund/origin",
"id": "4c977d466a76cec13b467b9ff499d48d0db1d479",
"size": "20012",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "vendor/k8s.io/kubernetes/pkg/scheduler/factory.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Awk",
"bytes": "921"
},
{
"name": "Dockerfile",
"bytes": "2240"
},
{
"name": "Go",
"bytes": "2330226"
},
{
"name": "Makefile",
"bytes": "6395"
},
{
"name": "Python",
"bytes": "14593"
},
{
"name": "Shell",
"bytes": "310343"
}
],
"symlink_target": ""
} |
using System;
using System.Threading.Tasks;
using Microsoft.Owin.Security.OAuth;
namespace TestSpaApp.Providers
{
public class ApplicationOAuthProvider : OAuthAuthorizationServerProvider
{
private readonly string _publicClientId;
public ApplicationOAuthProvider(string publicClientId)
{
if (publicClientId == null)
{
throw new ArgumentNullException("publicClientId");
}
_publicClientId = publicClientId;
}
public override Task ValidateClientRedirectUri(OAuthValidateClientRedirectUriContext context)
{
if (context.ClientId == _publicClientId)
{
Uri expectedRootUri = new Uri(context.Request.Uri, "/");
if (expectedRootUri.AbsoluteUri == context.RedirectUri)
{
context.Validated();
}
else if (context.ClientId == "web")
{
var expectedUri = new Uri(context.Request.Uri, "/");
context.Validated(expectedUri.AbsoluteUri);
}
}
return Task.FromResult<object>(null);
}
}
} | {
"content_hash": "f91ce92af3e0b42ff8190a8c0dc63d28",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 101,
"avg_line_length": 29.853658536585368,
"alnum_prop": 0.5620915032679739,
"repo_name": "idoychinov/Telerik_Academy_Homework",
"id": "1dae37059752c557686a8a26a9c496d72f08a105",
"size": "1226",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ASP.NETWeb Forms/1.IntroductionToAspNet/WebApps/TestSpaApp/Providers/ApplicationOAuthProvider.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "224148"
},
{
"name": "C#",
"bytes": "3952663"
},
{
"name": "CSS",
"bytes": "3475942"
},
{
"name": "CoffeeScript",
"bytes": "4453"
},
{
"name": "JavaScript",
"bytes": "8996873"
},
{
"name": "Pascal",
"bytes": "14823"
},
{
"name": "PowerShell",
"bytes": "1717649"
},
{
"name": "Puppet",
"bytes": "404631"
},
{
"name": "Shell",
"bytes": "315"
},
{
"name": "TypeScript",
"bytes": "11219"
},
{
"name": "XSLT",
"bytes": "2081"
}
],
"symlink_target": ""
} |
//
// (C) 2005 Vojtech Janota
//
// This library is free software, you can redistribute it
// and/or modify
// it under the terms of the GNU Lesser General Public License
// as published by the Free Software Foundation;
// either version 2 of the License, or any later version.
// The library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU Lesser General Public License for more details.
//
#ifndef __INET_BYTEARRAYMESSAGE_H
#define __INET_BYTEARRAYMESSAGE_H
#include "inet/common/ByteArrayMessage_m.h"
namespace inet {
/**
* Message that carries raw bytes. Used with emulation-related features.
*/
class ByteArrayMessage : public ByteArrayMessage_Base
{
public:
/**
* Constructor
*/
ByteArrayMessage(const char *name = NULL, int kind = 0) : ByteArrayMessage_Base(name, kind) {}
/**
* Copy constructor
*/
ByteArrayMessage(const ByteArrayMessage& other) : ByteArrayMessage_Base(other) {}
/**
* operator =
*/
ByteArrayMessage& operator=(const ByteArrayMessage& other) { ByteArrayMessage_Base::operator=(other); return *this; }
/**
* Creates and returns an exact copy of this object.
*/
virtual ByteArrayMessage *dup() const { return new ByteArrayMessage(*this); }
/**
* Set data from buffer
* @param ptr: pointer to buffer
* @param length: length of data
*/
virtual void setDataFromBuffer(const void *ptr, unsigned int length);
/**
* Add data from buffer to the end of existing content
* @param ptr: pointer to input buffer
* @param length: length of data
*/
virtual void addDataFromBuffer(const void *ptr, unsigned int length);
/**
* Copy data content to buffer
* @param ptr: pointer to output buffer
* @param length: length of buffer, maximum of copied bytes
* @return: length of copied data
*/
virtual unsigned int copyDataToBuffer(void *ptr, unsigned int length) const;
/**
* Truncate data content
* @param length: The number of bytes from the beginning of the content be removed
* Generate assert when not have enough bytes for truncation
*/
virtual void removePrefix(unsigned int length);
};
} // namespace inet
#endif // ifndef __INET_BYTEARRAYMESSAGE_H
| {
"content_hash": "a4ef0de03ad925beb9c4b8eb5b0cfad8",
"timestamp": "",
"source": "github",
"line_count": 81,
"max_line_length": 121,
"avg_line_length": 29.728395061728396,
"alnum_prop": 0.6839700996677741,
"repo_name": "googleinterns/vectio",
"id": "ef2004810d38ded3a0e997fb6794fc5dfd5472a5",
"size": "2408",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "inet/src/inet/common/ByteArrayMessage.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "12899"
},
{
"name": "C",
"bytes": "187862"
},
{
"name": "C++",
"bytes": "10383707"
},
{
"name": "CSS",
"bytes": "2751"
},
{
"name": "FreeMarker",
"bytes": "15828"
},
{
"name": "HTML",
"bytes": "41036"
},
{
"name": "Makefile",
"bytes": "5303"
},
{
"name": "Perl",
"bytes": "25486"
},
{
"name": "Python",
"bytes": "158836"
},
{
"name": "R",
"bytes": "51230"
},
{
"name": "Raku",
"bytes": "150"
},
{
"name": "Roff",
"bytes": "22957"
},
{
"name": "Shell",
"bytes": "21282"
},
{
"name": "Tcl",
"bytes": "18098"
},
{
"name": "XSLT",
"bytes": "14040"
}
],
"symlink_target": ""
} |
#ifndef BITCOINUNITS_H
#define BITCOINUNITS_H
#include <QString>
#include <QAbstractListModel>
/** Bitcoin unit definitions. Encapsulates parsing and formatting
and serves as list model for drop-down selection boxes.
*/
class BitcoinUnits: public QAbstractListModel
{
public:
explicit BitcoinUnits(QObject *parent);
/** Bitcoin units.
@note Source: https://en.bitcoin.it/wiki/Units . Please add only sensible ones
*/
enum Unit
{
BTC,
mBTC,
uBTC
};
//! @name Static API
//! Unit conversion and formatting
///@{
//! Get list of units, for drop-down box
static QList<Unit> availableUnits();
//! Is unit ID valid?
static bool valid(int unit);
//! Short name
static QString name(int unit);
//! Longer description
static QString description(int unit);
//! Number of Satoshis (1e-8) per unit
static qint64 factor(int unit);
//! Number of amount digits (to represent max number of coins)
static int amountDigits(int unit);
//! Number of decimals left
static int decimals(int unit);
//! Format as string
static QString format(int unit, qint64 amount, bool plussign=false);
//! Format as string (with unit)
static QString formatWithUnit(int unit, qint64 amount, bool plussign=false);
//! Format as a rounded string approximation for overview presentation
static QString formatOverviewRounded(qint64 amount);
//! Parse string to coin amount
static bool parse(int unit, const QString &value, qint64 *val_out);
///@}
//! @name AbstractListModel implementation
//! List model for unit drop-down selection box.
///@{
enum RoleIndex {
/** Unit identifier */
UnitRole = Qt::UserRole
};
int rowCount(const QModelIndex &parent) const;
QVariant data(const QModelIndex &index, int role) const;
///@}
private:
QList<BitcoinUnits::Unit> unitlist;
};
typedef BitcoinUnits::Unit BitcoinUnit;
#endif // BITCOINUNITS_H
| {
"content_hash": "36a7caa0d64100818145eda360c4d30c",
"timestamp": "",
"source": "github",
"line_count": 68,
"max_line_length": 84,
"avg_line_length": 29.602941176470587,
"alnum_prop": 0.6701440635866865,
"repo_name": "gridcoin/Gridcoin-Research",
"id": "70e455809270060fe023daaec2adf1a844e93cf1",
"size": "2013",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/qt/bitcoinunits.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "51312"
},
{
"name": "Batchfile",
"bytes": "50"
},
{
"name": "C",
"bytes": "56384"
},
{
"name": "C#",
"bytes": "21062"
},
{
"name": "C++",
"bytes": "3395818"
},
{
"name": "CSS",
"bytes": "1127"
},
{
"name": "HTML",
"bytes": "50640"
},
{
"name": "M4",
"bytes": "164343"
},
{
"name": "Makefile",
"bytes": "96605"
},
{
"name": "Objective-C",
"bytes": "858"
},
{
"name": "Objective-C++",
"bytes": "5716"
},
{
"name": "Python",
"bytes": "59129"
},
{
"name": "QMake",
"bytes": "15526"
},
{
"name": "Shell",
"bytes": "23430"
},
{
"name": "Visual Basic",
"bytes": "984007"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>angles: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.5.2 / angles - 8.7.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
angles
<small>
8.7.0
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-11-20 20:17:06 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-11-20 20:17:06 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-num base Num library distributed with the OCaml compiler
base-threads base
base-unix base
camlp5 7.14 Preprocessor-pretty-printer of OCaml
conf-findutils 1 Virtual package relying on findutils
conf-perl 2 Virtual package relying on perl
coq 8.5.2 Formal proof management system
num 0 The Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.03.0 The OCaml compiler (virtual package)
ocaml-base-compiler 4.03.0 Official 4.03.0 release
ocaml-config 1 OCaml Switch Configuration
# opam file:
opam-version: "2.0"
maintainer: "Hugo.Herbelin@inria.fr"
homepage: "https://github.com/coq-contribs/angles"
license: "Unknown"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/Angles"]
depends: [
"ocaml"
"coq" {>= "8.7" & < "8.8~"}
]
tags: [ "keyword: Pcoq" "keyword: geometry" "keyword: plane geometry" "keyword: oriented angles" "category: Mathematics/Geometry/General" "date: 2002-01-15" ]
authors: [ "Frédérique Guilhot <Frederique.Guilhot@sophia.inria.fr>" ]
bug-reports: "https://github.com/coq-contribs/angles/issues"
dev-repo: "git+https://github.com/coq-contribs/angles.git"
synopsis: "Formalization of the oriented angles theory"
description: """
The basis of the contribution is a formalization of the
theory of oriented angles of non-zero vectors. Then, we prove some
classical plane geometry theorems: the theorem which gives a necessary
and sufficient condition so that four points are cocyclic, the one
which shows that the reflected points with respect to the sides of a
triangle orthocenter are on its circumscribed circle, the Simson's
theorem and the Napoleon's theorem. The reader can refer to the
associated research report (http://www-sop.inria.fr/lemme/FGRR.ps) and
the README file of the contribution."""
flags: light-uninstall
url {
src: "https://github.com/coq-contribs/angles/archive/v8.7.0.tar.gz"
checksum: "md5=b9f406e5520b5fb3ad63bd88de4a035a"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-angles.8.7.0 coq.8.5.2</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.5.2).
The following dependencies couldn't be met:
- coq-angles -> coq >= 8.7 -> ocaml >= 4.05.0
base of this switch (use `--unlock-base' to force)
Your request can't be satisfied:
- No available version of coq satisfies the constraints
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-angles.8.7.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {
"content_hash": "cbcc365b51dfec2398c430708f0cb96f",
"timestamp": "",
"source": "github",
"line_count": 173,
"max_line_length": 218,
"avg_line_length": 43.323699421965316,
"alnum_prop": 0.5607738492328219,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "a5ce5e516c7544f8017e6bb15e9d7705250b628c",
"size": "7522",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.03.0-2.0.5/released/8.5.2/angles/8.7.0.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
sudo apt-get install --only-upgrade libidn=1.15-2+deb6u2 -y
| {
"content_hash": "59829096a6a1c29764e3fc9aab0ddb0d",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 59,
"avg_line_length": 60,
"alnum_prop": 0.75,
"repo_name": "Cyberwatch/cbw-security-fixes",
"id": "1f53698df34f82257483568d211520e48eec95ba",
"size": "588",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Debian_6_(Squeeze)/x86_64/2015/DLA-291-1.sh",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Shell",
"bytes": "26564468"
}
],
"symlink_target": ""
} |
var expect = require('chai').expect;
describe('<%= _.capitalize(name) %>Controller', function () {
it("Should be a passing spec." , function () {
expect(true).to.be.ok;
});
}); | {
"content_hash": "c48df111128570c4f400ff6d55e1212c",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 61,
"avg_line_length": 21.666666666666668,
"alnum_prop": 0.5743589743589743,
"repo_name": "brucecoddington/generator-mixtape",
"id": "f88bc66236563729fa52fa7b1159a9368c8f2d8c",
"size": "195",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "server-controller/templates/_spec.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "33990"
},
{
"name": "JavaScript",
"bytes": "84604"
}
],
"symlink_target": ""
} |
FactoryBot.define do
factory :note do
patient
full_text { 'behold, a note' }
created_by { FactoryBot.create(:user) }
end
end
| {
"content_hash": "b4ce591deb0f87a014f5b0873e2cb79f",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 43,
"avg_line_length": 20.142857142857142,
"alnum_prop": 0.6524822695035462,
"repo_name": "lomky/dcaf_case_management",
"id": "23ff015e6c110d4cedfb261f78ed6209e1d444e4",
"size": "141",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/factories/note.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "13868"
},
{
"name": "CoffeeScript",
"bytes": "2888"
},
{
"name": "Dockerfile",
"bytes": "1280"
},
{
"name": "HTML",
"bytes": "92675"
},
{
"name": "JavaScript",
"bytes": "25090"
},
{
"name": "Ruby",
"bytes": "450746"
},
{
"name": "Shell",
"bytes": "227"
}
],
"symlink_target": ""
} |
require 'spec_helper'
describe 'glance::backend::swift' do
let :facts do
{
:osfamily => 'Debian'
}
end
let :params do
{
:swift_store_user => 'user',
:swift_store_key => 'key',
}
end
let :pre_condition do
'class { "glance::api": keystone_password => "pass" }'
end
it { should contain_glance_api_config('DEFAULT/default_store').with_value('swift') }
it { should contain_glance_api_config('DEFAULT/swift_store_key').with_value('key') }
it { should contain_glance_api_config('DEFAULT/swift_store_user').with_value('user') }
it { should contain_glance_api_config('DEFAULT/swift_store_auth_version').with_value('2') }
it { should contain_glance_api_config('DEFAULT/swift_store_auth_address').with_value('127.0.0.1:5000/v2.0/') }
it { should contain_glance_api_config('DEFAULT/swift_store_container').with_value('glance') }
it { should contain_glance_api_config('DEFAULT/swift_store_create_container_on_put').with_value('False') }
describe 'when overriding datadir' do
let :params do
{
:swift_store_user => 'user',
:swift_store_key => 'key',
:swift_store_auth_version => '1',
:swift_store_auth_address => '127.0.0.2:8080/v1.0/',
:swift_store_container => 'swift',
:swift_store_create_container_on_put => 'True'
}
end
it { should contain_glance_api_config('DEFAULT/swift_store_container').with_value('swift') }
it { should contain_glance_api_config('DEFAULT/swift_store_create_container_on_put').with_value('True') }
it { should contain_glance_api_config('DEFAULT/swift_store_auth_version').with_value('1') }
it { should contain_glance_api_config('DEFAULT/swift_store_auth_address').with_value('127.0.0.2:8080/v1.0/') }
end
end
| {
"content_hash": "a9c0a0e4173f899946f4dfc3cd3f06c1",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 114,
"avg_line_length": 40.13333333333333,
"alnum_prop": 0.6423034330011074,
"repo_name": "nlopes/puppet-glance",
"id": "3ae406567b58e0b38522fedf23007264c6b8606e",
"size": "1806",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "spec/classes/glance_backend_swift_spec.rb",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
module Stellar
class KeyPair
def self.from_seed(seed)
seed_bytes = Util::Base58.stellar.check_decode(:seed, seed)
from_raw_seed seed_bytes
end
def self.from_raw_seed(seed_bytes)
secret_key = RbNaCl::SigningKey.new(seed_bytes)
public_key = secret_key.verify_key
new(public_key, secret_key)
end
def self.from_public_key(pk_bytes)
public_key = RbNaCl::VerifyKey.new(pk_bytes)
new(public_key)
end
def self.from_address(address)
pk_bytes = Util::Base58.stellar.check_decode(:account_id, address)
from_public_key(pk_bytes)
end
def self.random
secret_key = RbNaCl::SigningKey.generate
public_key = secret_key.verify_key
new(public_key, secret_key)
end
def initialize(public_key, secret_key=nil)
@public_key = public_key
@secret_key = secret_key
end
def public_key
@public_key.to_bytes
end
def public_key_hint
public_key.slice(0, 4)
end
def raw_seed
@secret_key.to_bytes
end
def rbnacl_signing_key
@secret_key
end
def rbnacl_verify_key
@public_key
end
def address
pk_bytes = public_key
Util::Base58.stellar.check_encode(:account_id, pk_bytes)
end
def seed
raise "no private key" if @secret_key.nil?
#TODO: improve the error class above
seed_bytes = raw_seed
encoder = Util::Base58.stellar.check_encode(:seed, seed_bytes)
end
def sign?
!@secret_key.nil?
end
def sign(message)
raise "no private key" if @secret_key.nil?
#TODO: improve the error class above
@secret_key.sign(message)
end
def sign_decorated(message)
raw_signature = sign(message)
Stellar::DecoratedSignature.new({
hint: public_key_hint,
signature: raw_signature
})
end
def verify(signature, message)
@public_key.verify(signature, message)
rescue RbNaCl::LengthError
false
rescue RbNaCl::BadSignatureError
false
end
end
end | {
"content_hash": "8b82579453c4bee230bdfa91a85f2492",
"timestamp": "",
"source": "github",
"line_count": 94,
"max_line_length": 72,
"avg_line_length": 22.0531914893617,
"alnum_prop": 0.6251808972503617,
"repo_name": "Payshare/ruby-stellar-base",
"id": "d9d80dc7ce349279839acca07320021dfa2a47bc",
"size": "2073",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/stellar/key_pair.rb",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Logos",
"bytes": "21967"
},
{
"name": "Ruby",
"bytes": "104029"
}
],
"symlink_target": ""
} |
package com.yqboots.fss.core.convert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationPropertiesBinding;
import org.springframework.core.convert.converter.Converter;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
* A Spring Converter for converting from String to NIO Path.
* <p/>
* <p>Used to convert file path related properties.</p>
*
* @author Eric H B Zhan
* @since 1.0.0
*/
@ConfigurationPropertiesBinding
public class StringToPathConverter implements Converter<String, Path> {
private static final Logger LOG = LoggerFactory.getLogger(StringToPathConverter.class);
/**
* Convert the source object of type {@code S} to target type {@code T}.
*
* @param source the source object to convert, which must be an instance of {@code S} (never {@code null})
* @return the converted object, which must be an instance of {@code T} (potentially {@code null})
* @throws IllegalArgumentException if the source cannot be converted to the desired target type
*/
@Override
public Path convert(final String source) {
Path result = Paths.get(source.replace("\\", File.separator));
if (!Files.exists(result)) {
LOG.error("Path not found [{}]", result);
}
return result;
}
}
| {
"content_hash": "f5fac58cfccd43fd01be3f9ba24c3595",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 110,
"avg_line_length": 34.170731707317074,
"alnum_prop": 0.7037830121341898,
"repo_name": "zhanhongbo1112/trunk",
"id": "61eae96b8cc37514d67f8260dd913289438164aa",
"size": "1401",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "yqboots-fss/yqboots-fss-core/src/main/java/com/yqboots/fss/core/convert/StringToPathConverter.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "105289"
},
{
"name": "HTML",
"bytes": "26241"
},
{
"name": "Java",
"bytes": "82035"
},
{
"name": "JavaScript",
"bytes": "7741"
}
],
"symlink_target": ""
} |
wget https://dist.thingsboard.io/thingsboard-3.0pe.rpm
| {
"content_hash": "c818bb7eeee4c1dbe0235d7603ced7ff",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 54,
"avg_line_length": 55,
"alnum_prop": 0.8,
"repo_name": "thingsboard/thingsboard.github.io",
"id": "d6afa2f801f23c5b5a07bd4d2de6ed9e398a0cb0",
"size": "55",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "docs/user-guide/install/pe/resources/3.0.0pe/thingsboard-centos-download.sh",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "24272"
},
{
"name": "Dockerfile",
"bytes": "237"
},
{
"name": "HTML",
"bytes": "210261"
},
{
"name": "JavaScript",
"bytes": "36100"
},
{
"name": "Makefile",
"bytes": "553"
},
{
"name": "Ruby",
"bytes": "599"
},
{
"name": "SCSS",
"bytes": "5189"
},
{
"name": "Sass",
"bytes": "309300"
},
{
"name": "Shell",
"bytes": "9108"
}
],
"symlink_target": ""
} |
var Loader = require('pomelo-loader');
var Gateway = require('./gateway');
var loadRemoteServices = function(paths, context) {
var res = {},
item, m;
for (var i = 0, l = paths.length; i < l; i++) {
item = paths[i];
m = Loader.load(item.path, context);
if (m) {
createNamespace(item.namespace, res);
for (var s in m) {
res[item.namespace][s] = m[s];
}
}
}
return res;
};
var createNamespace = function(namespace, proxies) {
proxies[namespace] = proxies[namespace] || {};
};
/**
* Create rpc server.
*
* @param {Object} opts construct parameters
* opts.port {Number|String} rpc server listen port
* opts.paths {Array} remote service code paths, [{namespace, path}, ...]
* opts.context {Object} context for remote service
* opts.acceptorFactory {Object} (optionals)acceptorFactory.create(opts, cb)
* @return {Object} rpc server instance
*/
module.exports.create = function(opts) {
if (!opts || !opts.port || opts.port < 0 || !opts.paths) {
throw new Error('opts.port or opts.paths invalid.');
}
var services = loadRemoteServices(opts.paths, opts.context);
opts.services = services;
var gateway = Gateway.create(opts);
return gateway;
};
// module.exports.WSAcceptor = require('./acceptors/ws-acceptor');
// module.exports.TcpAcceptor = require('./acceptors/tcp-acceptor');
module.exports.MqttAcceptor = require('./acceptors/mqtt-acceptor'); | {
"content_hash": "12b219ae5141942f993db8085d261eb9",
"timestamp": "",
"source": "github",
"line_count": 48,
"max_line_length": 98,
"avg_line_length": 31.729166666666668,
"alnum_prop": 0.6172028890347997,
"repo_name": "jiangzhuo/pomelo-rpc",
"id": "fad7113cc4fa43aa599669784da11aa73af910da",
"size": "1523",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "lib/rpc-server/server.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "127358"
},
{
"name": "Makefile",
"bytes": "365"
}
],
"symlink_target": ""
} |
package projects.search;
import java.util.Iterator;
public interface Search
{
public Iterator<String> search(String... words) ;
//public Iterator<String> search(String str)
}
| {
"content_hash": "ddcc6b8c6e25c8dd2610e6075c227e7e",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 53,
"avg_line_length": 17,
"alnum_prop": 0.7272727272727273,
"repo_name": "afs/AFS-Dev",
"id": "e362c0c5179b8cd160ce4a0d9163cb171daa6493",
"size": "873",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/projects/search/Search.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "633112"
},
{
"name": "Scala",
"bytes": "3182"
},
{
"name": "Shell",
"bytes": "4891"
}
],
"symlink_target": ""
} |
/************************************************************************************//**
* @file CCountDown.cpp
* @brief CCountDown class implementation
* @author Ralph Deane
****************************************************************************************/
#include "RabidFramework.h"
extern geSound_Def *SPool_Sound(const char *SName);
/* ------------------------------------------------------------------------------------ */
// Constructor
/* ------------------------------------------------------------------------------------ */
CCountDown::CCountDown()
{
geEntity_EntitySet *pSet;
geEntity *pEntity;
// Ok, see if we have any CountDownTimer entities at all
pSet = geWorld_GetEntitySet(CCD->World(), "CountDownTimer");
if(!pSet)
return;
// Look through all of our CountDownTimers
for(pEntity=geEntity_EntitySetGetNextEntity(pSet, NULL); pEntity;
pEntity=geEntity_EntitySetGetNextEntity(pSet, pEntity))
{
CountDownTimer *pItem = (CountDownTimer*)geEntity_GetUserData(pEntity);
if(EffectC_IsStringNull(pItem->szEntityName))
{
char szName[128];
geEntity_GetName(pEntity, szName, 128);
pItem->szEntityName = szName;
}
// Ok, put this entity into the Global Entity Registry
CCD->EntityRegistry()->AddEntity(pItem->szEntityName, "CountDownTimer");
pItem->active = GE_FALSE;
pItem->alive = GE_FALSE;
pItem->Time = 0.0f;
pItem->OldState = GE_FALSE;
pItem->bState = GE_FALSE;
if(!EffectC_IsStringNull(pItem->Attribute))
{
CPersistentAttributes *theInv = CCD->ActorManager()->Inventory(CCD->Player()->GetActor());
if(theInv->Has(pItem->Attribute))
{
pItem->alive = GE_TRUE;
theInv->SetValueLimits(pItem->Attribute, 0, (int)pItem->TimeAmt);
theInv->Set(pItem->Attribute, 0);
}
}
if(!EffectC_IsStringNull(pItem->SoundFile))
SPool_Sound(pItem->SoundFile);
pItem->index = -1;
}
}
/* ------------------------------------------------------------------------------------ */
// Destructor
/* ------------------------------------------------------------------------------------ */
CCountDown::~CCountDown()
{
}
/* ------------------------------------------------------------------------------------ */
// Tick
/* ------------------------------------------------------------------------------------ */
void CCountDown::Tick(geFloat dwTicks)
{
geEntity_EntitySet *pSet;
geEntity *pEntity;
// Ok, see if we have any CountDownTimer entities at all
pSet = geWorld_GetEntitySet(CCD->World(), "CountDownTimer");
if(!pSet)
return;
// Look through all of our CountDownTimers
for(pEntity=geEntity_EntitySetGetNextEntity(pSet, NULL); pEntity;
pEntity=geEntity_EntitySetGetNextEntity(pSet, pEntity))
{
CountDownTimer *pItem = (CountDownTimer*)geEntity_GetUserData(pEntity);
CPersistentAttributes *theInv = CCD->ActorManager()->Inventory(CCD->Player()->GetActor());
if(!EffectC_IsStringNull(pItem->StopTrigger))
{
if(GetTriggerState(pItem->StopTrigger))
{
pItem->active = GE_FALSE;
pItem->bState = GE_FALSE;
if(pItem->index!=-1)
{
CCD->EffectManager()->Item_Delete(EFF_SND, pItem->index);
pItem->index = -1;
}
continue;
}
}
if(!pItem->active)
{
if(!EffectC_IsStringNull(pItem->TriggerName))
{
if(GetTriggerState(pItem->TriggerName))
{
if(!pItem->OldState)
{
pItem->OldState = GE_TRUE;
pItem->Time = pItem->TimeAmt;
pItem->active = GE_TRUE;
pItem->bState = GE_FALSE;
if(pItem->alive)
theInv->Set(pItem->Attribute, (int)pItem->Time);
if(!EffectC_IsStringNull(pItem->SoundFile))
{
Snd Sound;
memset(&Sound, 0, sizeof(Sound));
CCD->ActorManager()->GetPosition(CCD->Player()->GetActor(), &(Sound.Pos));
Sound.Min=CCD->GetAudibleRadius();
Sound.Loop = GE_TRUE;
Sound.SoundDef = SPool_Sound(pItem->SoundFile);
pItem->index = CCD->EffectManager()->Item_Add(EFF_SND, (void*)&Sound);
}
}
}
else
pItem->OldState = GE_FALSE;
}
}
else
{
pItem->Time -= (dwTicks*0.001f);
if(pItem->Time <= 0.0f)
{
pItem->active = GE_FALSE;
pItem->bState = GE_TRUE;
if(pItem->index != -1)
{
CCD->EffectManager()->Item_Delete(EFF_SND, pItem->index);
pItem->index = -1;
}
}
if(pItem->alive)
theInv->Set(pItem->Attribute, (int)pItem->Time);
}
}
}
// ******************** CRGF Overrides ********************
/* ------------------------------------------------------------------------------------ */
// LocateEntity
//
// Given a name, locate the desired item in the currently loaded level
// ..and return it's user data.
/* ------------------------------------------------------------------------------------ */
int CCountDown::LocateEntity(const char *szName, void **pEntityData)
{
geEntity_EntitySet *pSet;
geEntity *pEntity;
// Ok, check to see if there are CountDownTimers in this world
pSet = geWorld_GetEntitySet(CCD->World(), "CountDownTimer");
if(!pSet)
return RGF_NOT_FOUND;
// Ok, we have CountDownTimers. Dig through 'em all.
for(pEntity=geEntity_EntitySetGetNextEntity(pSet, NULL); pEntity;
pEntity=geEntity_EntitySetGetNextEntity(pSet, pEntity))
{
CountDownTimer *pTheEntity = (CountDownTimer*)geEntity_GetUserData(pEntity);
if(!strcmp(pTheEntity->szEntityName, szName))
{
*pEntityData = (void*)pTheEntity;
return RGF_SUCCESS;
}
}
return RGF_NOT_FOUND; // Sorry, no such entity here
}
/* ------------------------------------------------------------------------------------ */
// SaveTo
//
// Save the current state of every CountDownTimer in the current world
// ..off to an open file.
/* ------------------------------------------------------------------------------------ */
int CCountDown::SaveTo(FILE *SaveFD, bool type)
{
geEntity_EntitySet *pSet;
geEntity *pEntity;
// Ok, check to see if there are CountDownTimers in this world
pSet = geWorld_GetEntitySet(CCD->World(), "CountDownTimer");
if(!pSet)
return RGF_SUCCESS;
// Ok, we have CountDownTimers somewhere. Dig through 'em all.
for(pEntity=geEntity_EntitySetGetNextEntity(pSet, NULL); pEntity;
pEntity=geEntity_EntitySetGetNextEntity(pSet, pEntity))
{
CountDownTimer *pSource = (CountDownTimer*)geEntity_GetUserData(pEntity);
WRITEDATA(type, &pSource->active, sizeof(geBoolean), 1, SaveFD);
WRITEDATA(type, &pSource->bState, sizeof(geBoolean), 1, SaveFD);
WRITEDATA(type, &pSource->OldState, sizeof(geBoolean), 1, SaveFD);
WRITEDATA(type, &pSource->Time, sizeof(float), 1, SaveFD);
}
return RGF_SUCCESS;
}
/* ------------------------------------------------------------------------------------ */
// RestoreFrom
//
// Restore the state of every CountDownTimer in the current world from an
// ..open file.
/* ------------------------------------------------------------------------------------ */
int CCountDown::RestoreFrom(FILE *RestoreFD, bool type)
{
geEntity_EntitySet *pSet;
geEntity *pEntity;
// Ok, check to see if there are CountDownTimers in this world
pSet = geWorld_GetEntitySet(CCD->World(), "CountDownTimer");
if(!pSet)
return RGF_SUCCESS;
for(pEntity=geEntity_EntitySetGetNextEntity(pSet, NULL); pEntity;
pEntity=geEntity_EntitySetGetNextEntity(pSet, pEntity))
{
CountDownTimer *pSource = (CountDownTimer*)geEntity_GetUserData(pEntity);
READDATA(type, &pSource->active, sizeof(geBoolean), 1, RestoreFD);
READDATA(type, &pSource->bState, sizeof(geBoolean), 1, RestoreFD);
READDATA(type, &pSource->OldState, sizeof(geBoolean), 1, RestoreFD);
READDATA(type, &pSource->Time, sizeof(float), 1, RestoreFD);
}
return RGF_SUCCESS;
}
/* ----------------------------------- END OF FILE ------------------------------------ */
| {
"content_hash": "bedfd54a31c2cb78fedda8fd2c65e57f",
"timestamp": "",
"source": "github",
"line_count": 263,
"max_line_length": 93,
"avg_line_length": 29.482889733840302,
"alnum_prop": 0.5619035336600464,
"repo_name": "RealityFactory/RealityFactory",
"id": "a644f21b2f76c20eda4d8d6afab70405097ab2a6",
"size": "7754",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "CCountDown.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "342607"
},
{
"name": "C++",
"bytes": "4182344"
},
{
"name": "Haxe",
"bytes": "1893"
},
{
"name": "Objective-C",
"bytes": "163123"
}
],
"symlink_target": ""
} |
macro(_list_append_deduplicate listname)
if(NOT "${ARGN}" STREQUAL "")
if(${listname})
list(REMOVE_ITEM ${listname} ${ARGN})
endif()
list(APPEND ${listname} ${ARGN})
endif()
endmacro()
# append elements to a list if they are not already in the list
# copied from catkin/cmake/list_append_unique.cmake to keep pkgConfig
# self contained
macro(_list_append_unique listname)
foreach(_item ${ARGN})
list(FIND ${listname} ${_item} _index)
if(_index EQUAL -1)
list(APPEND ${listname} ${_item})
endif()
endforeach()
endmacro()
# pack a list of libraries with optional build configuration keywords
# copied from catkin/cmake/catkin_libraries.cmake to keep pkgConfig
# self contained
macro(_pack_libraries_with_build_configuration VAR)
set(${VAR} "")
set(_argn ${ARGN})
list(LENGTH _argn _count)
set(_index 0)
while(${_index} LESS ${_count})
list(GET _argn ${_index} lib)
if("${lib}" MATCHES "^debug|optimized|general$")
math(EXPR _index "${_index} + 1")
if(${_index} EQUAL ${_count})
message(FATAL_ERROR "_pack_libraries_with_build_configuration() the list of libraries '${ARGN}' ends with '${lib}' which is a build configuration keyword and must be followed by a library")
endif()
list(GET _argn ${_index} library)
list(APPEND ${VAR} "${lib}${CATKIN_BUILD_CONFIGURATION_KEYWORD_SEPARATOR}${library}")
else()
list(APPEND ${VAR} "${lib}")
endif()
math(EXPR _index "${_index} + 1")
endwhile()
endmacro()
# unpack a list of libraries with optional build configuration keyword prefixes
# copied from catkin/cmake/catkin_libraries.cmake to keep pkgConfig
# self contained
macro(_unpack_libraries_with_build_configuration VAR)
set(${VAR} "")
foreach(lib ${ARGN})
string(REGEX REPLACE "^(debug|optimized|general)${CATKIN_BUILD_CONFIGURATION_KEYWORD_SEPARATOR}(.+)$" "\\1;\\2" lib "${lib}")
list(APPEND ${VAR} "${lib}")
endforeach()
endmacro()
if(dlut_pc_odom_CONFIG_INCLUDED)
return()
endif()
set(dlut_pc_odom_CONFIG_INCLUDED TRUE)
# set variables for source/devel/install prefixes
if("TRUE" STREQUAL "TRUE")
set(dlut_pc_odom_SOURCE_PREFIX /home/rob/catkin_ws/src/dlut_pc_odom)
set(dlut_pc_odom_DEVEL_PREFIX /home/rob/catkin_ws/devel)
set(dlut_pc_odom_INSTALL_PREFIX "")
set(dlut_pc_odom_PREFIX ${dlut_pc_odom_DEVEL_PREFIX})
else()
set(dlut_pc_odom_SOURCE_PREFIX "")
set(dlut_pc_odom_DEVEL_PREFIX "")
set(dlut_pc_odom_INSTALL_PREFIX /home/rob/catkin_ws/install)
set(dlut_pc_odom_PREFIX ${dlut_pc_odom_INSTALL_PREFIX})
endif()
# warn when using a deprecated package
if(NOT "" STREQUAL "")
set(_msg "WARNING: package 'dlut_pc_odom' is deprecated")
# append custom deprecation text if available
if(NOT "" STREQUAL "TRUE")
set(_msg "${_msg} ()")
endif()
message("${_msg}")
endif()
# flag project as catkin-based to distinguish if a find_package()-ed project is a catkin project
set(dlut_pc_odom_FOUND_CATKIN_PROJECT TRUE)
if(NOT "/home/rob/catkin_ws/devel/include;/home/rob/catkin_ws/src/dlut_pc_odom/include" STREQUAL "")
set(dlut_pc_odom_INCLUDE_DIRS "")
set(_include_dirs "/home/rob/catkin_ws/devel/include;/home/rob/catkin_ws/src/dlut_pc_odom/include")
foreach(idir ${_include_dirs})
if(IS_ABSOLUTE ${idir} AND IS_DIRECTORY ${idir})
set(include ${idir})
elseif("${idir}" STREQUAL "include")
get_filename_component(include "${dlut_pc_odom_DIR}/../../../include" ABSOLUTE)
if(NOT IS_DIRECTORY ${include})
message(FATAL_ERROR "Project 'dlut_pc_odom' specifies '${idir}' as an include dir, which is not found. It does not exist in '${include}'. Ask the maintainer 'Zhuang Yan,Yan Fei,Dong Bingbing>wu <zhuang@dlut.edu.cn>' to fix it.")
endif()
else()
message(FATAL_ERROR "Project 'dlut_pc_odom' specifies '${idir}' as an include dir, which is not found. It does neither exist as an absolute directory nor in '/home/rob/catkin_ws/src/dlut_pc_odom/${idir}'. Ask the maintainer 'Zhuang Yan,Yan Fei,Dong Bingbing>wu <zhuang@dlut.edu.cn>' to fix it.")
endif()
_list_append_unique(dlut_pc_odom_INCLUDE_DIRS ${include})
endforeach()
endif()
set(libraries "")
foreach(library ${libraries})
# keep build configuration keywords, target names and absolute libraries as-is
if("${library}" MATCHES "^debug|optimized|general$")
list(APPEND dlut_pc_odom_LIBRARIES ${library})
elseif(TARGET ${library})
list(APPEND dlut_pc_odom_LIBRARIES ${library})
elseif(IS_ABSOLUTE ${library})
list(APPEND dlut_pc_odom_LIBRARIES ${library})
else()
set(lib_path "")
set(lib "${library}-NOTFOUND")
# since the path where the library is found is returned we have to iterate over the paths manually
foreach(path /home/rob/catkin_ws/devel/lib;/home/rob/catkin_ws/devel/lib;/opt/ros/indigo/lib)
find_library(lib ${library}
PATHS ${path}
NO_DEFAULT_PATH NO_CMAKE_FIND_ROOT_PATH)
if(lib)
set(lib_path ${path})
break()
endif()
endforeach()
if(lib)
_list_append_unique(dlut_pc_odom_LIBRARY_DIRS ${lib_path})
list(APPEND dlut_pc_odom_LIBRARIES ${lib})
else()
# as a fall back for non-catkin libraries try to search globally
find_library(lib ${library})
if(NOT lib)
message(FATAL_ERROR "Project '${PROJECT_NAME}' tried to find library '${library}'. The library is neither a target nor built/installed properly. Did you compile project 'dlut_pc_odom'? Did you find_package() it before the subdirectory containing its code is included?")
endif()
list(APPEND dlut_pc_odom_LIBRARIES ${lib})
endif()
endif()
endforeach()
set(dlut_pc_odom_EXPORTED_TARGETS "dlut_pc_odom_generate_messages_cpp;dlut_pc_odom_generate_messages_lisp;dlut_pc_odom_generate_messages_py")
# create dummy targets for exported code generation targets to make life of users easier
foreach(t ${dlut_pc_odom_EXPORTED_TARGETS})
if(NOT TARGET ${t})
add_custom_target(${t})
endif()
endforeach()
set(depends "")
foreach(depend ${depends})
string(REPLACE " " ";" depend_list ${depend})
# the package name of the dependency must be kept in a unique variable so that it is not overwritten in recursive calls
list(GET depend_list 0 dlut_pc_odom_dep)
list(LENGTH depend_list count)
if(${count} EQUAL 1)
# simple dependencies must only be find_package()-ed once
if(NOT ${dlut_pc_odom_dep}_FOUND)
find_package(${dlut_pc_odom_dep} REQUIRED)
endif()
else()
# dependencies with components must be find_package()-ed again
list(REMOVE_AT depend_list 0)
find_package(${dlut_pc_odom_dep} REQUIRED ${depend_list})
endif()
_list_append_unique(dlut_pc_odom_INCLUDE_DIRS ${${dlut_pc_odom_dep}_INCLUDE_DIRS})
# merge build configuration keywords with library names to correctly deduplicate
_pack_libraries_with_build_configuration(dlut_pc_odom_LIBRARIES ${dlut_pc_odom_LIBRARIES})
_pack_libraries_with_build_configuration(_libraries ${${dlut_pc_odom_dep}_LIBRARIES})
_list_append_deduplicate(dlut_pc_odom_LIBRARIES ${_libraries})
# undo build configuration keyword merging after deduplication
_unpack_libraries_with_build_configuration(dlut_pc_odom_LIBRARIES ${dlut_pc_odom_LIBRARIES})
_list_append_unique(dlut_pc_odom_LIBRARY_DIRS ${${dlut_pc_odom_dep}_LIBRARY_DIRS})
list(APPEND dlut_pc_odom_EXPORTED_TARGETS ${${dlut_pc_odom_dep}_EXPORTED_TARGETS})
endforeach()
set(pkg_cfg_extras "dlut_pc_odom-msg-extras.cmake")
foreach(extra ${pkg_cfg_extras})
if(NOT IS_ABSOLUTE ${extra})
set(extra ${dlut_pc_odom_DIR}/${extra})
endif()
include(${extra})
endforeach()
| {
"content_hash": "84ed0cc625fc679028272bfde656b00a",
"timestamp": "",
"source": "github",
"line_count": 186,
"max_line_length": 303,
"avg_line_length": 41.016129032258064,
"alnum_prop": 0.6915716345523659,
"repo_name": "WuNL/rob_workspace",
"id": "9dead1cb33690cd996c2ebda2e6ce700da12395f",
"size": "7853",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "devel/share/dlut_pc_odom/cmake/dlut_pc_odomConfig.cmake",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "390378"
},
{
"name": "Common Lisp",
"bytes": "107702"
},
{
"name": "Python",
"bytes": "24546"
},
{
"name": "Shell",
"bytes": "19053"
}
],
"symlink_target": ""
} |
/*this is a common css class file write by wodrow*/
.height_100_percent{height: 100%}
.min_height_100_percent{min-height: 100%}
.height_auto{height: auto;} | {
"content_hash": "c4bf2b6875abaf4bb7a828387598f7c9",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 51,
"avg_line_length": 38.75,
"alnum_prop": 0.7354838709677419,
"repo_name": "wodrow/yii2mall2",
"id": "ad560b6152c3340d76d2d151b6cd1d413968d74d",
"size": "155",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "frontend/web/css/common.css",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ApacheConf",
"bytes": "844"
},
{
"name": "Batchfile",
"bytes": "1541"
},
{
"name": "CSS",
"bytes": "3125"
},
{
"name": "HTML",
"bytes": "244112"
},
{
"name": "Makefile",
"bytes": "3999"
},
{
"name": "PHP",
"bytes": "930202"
}
],
"symlink_target": ""
} |
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
Copyright (C) 2011 Klaus Spanderen
This file is part of QuantLib, a free-software/open-source library
for financial quantitative analysts and developers - http://quantlib.org/
QuantLib is free software: you can redistribute it and/or modify it
under the terms of the QuantLib license. You should have received a
copy of the license along with this program; if not, please email
<quantlib-dev@lists.sf.net>. The license is also available online at
<http://quantlib.org/license.shtml>.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the license for more details.
*/
/*! \file gemanroncoroniprocess.cpp
\brief Geman-Roncoroni process
*/
#include <ql/math/functional.hpp>
#include <ql/processes/eulerdiscretization.hpp>
#include <ql/experimental/processes/gemanroncoroniprocess.hpp>
namespace QuantLib {
GemanRoncoroniProcess::GemanRoncoroniProcess(
Real x0,
Real alpha, Real beta,
Real gamma, Real delta,
Real eps, Real zeta, Real d,
Real k, Real tau,
Real sig2, Real a, Real b,
Real theta1, Real theta2, Real theta3,
Real psi)
: StochasticProcess1D(boost::shared_ptr<discretization>(
new EulerDiscretization)),
x0_(x0),
alpha_(alpha), beta_(beta),
gamma_(gamma), delta_(delta),
eps_(eps), zeta_(zeta), d_(d),
k_(k), tau_(tau),
sig2_(sig2), a_(a), b_(b),
theta1_(theta1), theta2_(theta2), theta3_(theta3),
psi_(psi) {
}
Real GemanRoncoroniProcess::x0() const {
return x0_;
}
Real GemanRoncoroniProcess::drift(Time t, Real x) const {
const Real mu = alpha_ + beta_*t + gamma_*std::cos(eps_+2*M_PI*t)
+ delta_*std::cos(zeta_+4*M_PI*t);
const Real muPrime = beta_ - gamma_*2*M_PI*std::sin(eps_+2*M_PI*t)
- delta_*4*M_PI*std::sin(zeta_+4*M_PI*t);
return muPrime + theta1_*(mu-x);
}
Real GemanRoncoroniProcess::diffusion(Time t, Real /*x*/) const {
return std::sqrt(sig2_ + a_*square<Real>()(std::cos(M_PI*t+b_)));
}
Real GemanRoncoroniProcess::stdDeviation(Time t0, Real /*x0*/, Time dt) const {
const Volatility sig2t = sig2_+a_*square<Real>()(std::cos(M_PI*t0+b_));
return std::sqrt(sig2t/(2*theta1_)*(1.0-std::exp(-2*theta1_*dt)));
}
Real GemanRoncoroniProcess::evolve(Time t0, Real x0,
Time dt, Real dw) const {
// random number generator for the jump part
if (!urng_) {
typedef PseudoRandom::urng_type urng_type;
urng_ = boost::shared_ptr<urng_type>(
new urng_type((unsigned long)(1234ul*dw+56789ul)));
}
Array du(3);
du[0] = urng_->next().value;
du[1] = urng_->next().value;
return evolve(t0, x0, dt, dw, du);
}
Real GemanRoncoroniProcess::evolve(Time t0, Real x0, Time dt,
Real dw, const Array& du) const {
Real retVal;
const Time t = t0 + 0.5*dt;
const Real mu = alpha_ + beta_*t + gamma_*std::cos(eps_ +2*M_PI*t)
+ delta_*std::cos(zeta_+4*M_PI*t);
const Real j = -1.0/theta3_
*std::log(1.0+du[1]*(std::exp(-theta3_*psi_)-1.0));
if (x0 <= mu+d_) {
retVal = StochasticProcess1D::evolve(t, x0, dt, dw);
const Real jumpIntensity
= theta2_*(2.0/(1+std::fabs(std::sin(M_PI*(t-tau_)/k_)))-1);
const Time interarrival = -1.0/jumpIntensity*std::log(du[0]);
if (interarrival < dt) {
retVal += j;
}
}
else {
retVal = x0-j;
}
return retVal;
}
}
| {
"content_hash": "e89ac73b21d6c435dd230aa0ac56e358",
"timestamp": "",
"source": "github",
"line_count": 117,
"max_line_length": 88,
"avg_line_length": 37.333333333333336,
"alnum_prop": 0.5224358974358975,
"repo_name": "applehackfoxus/Quantum-Trading",
"id": "053a2e0a0d1f9eff5c0ceb67146ae317972df0a4",
"size": "4368",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "QuantLib-1.4/ql/experimental/processes/gemanroncoroniprocess.cpp",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LiNGS.Common
{
/// <summary>
/// String markers used internally on the LiNGS System.
/// </summary>
public static class LiNGSMarkers
{
/// <summary>
/// The namespace used to identify the message.
/// </summary>
public static readonly string Namespace = "0L";
/// <summary>
/// Separator used when multiple data is joined together.
/// </summary>
public static readonly string Separator = "$";
/// <summary>
/// Indicates that the data is an Id.
/// </summary>
public static readonly string Id = Namespace + ":id";
/// <summary>
/// Indicates that the data is an SessionUserId.
/// </summary>
public static readonly string SessionUserId = Namespace + ":uid";
/// <summary>
/// Indicates that the data is a time offset.
/// </summary>
public static readonly string TimeOffset = Namespace + ":toffset";
/// <summary>
/// Indicates that an error has occurred.
/// </summary>
public static readonly string Error = Namespace + ":err";
/// <summary>
/// Indicates that the request was successful.
/// </summary>
public static readonly string Ok = Namespace + ":ok";
/// <summary>
/// Indicates that an object should be created.
/// </summary>
public static readonly string CreateObject = Namespace + ":ctobj";
/// <summary>
/// Indicates the type of an object.
/// </summary>
public static readonly string ObjectType = Namespace + ":otype";
/// <summary>
/// Indicates if the object was automatically created.
/// </summary>
public static readonly string AutoCreatedObject = Namespace + ":o:";
/// <summary>
/// Indicates that an object should be destroyed.
/// </summary>
public static readonly string DestroyObject = Namespace + ":dtobj";
/// <summary>
/// Indicates that a saved state will be used.
/// </summary>
public static readonly string UsingSavedState = Namespace + ":scached";
/// <summary>
/// Indicates a reason for the response.
/// </summary>
public static readonly string Reason = Namespace + ":reason";
/// <summary>
/// Indicates that an object should be activated/deactivated.
/// </summary>
public static readonly string SetActive = Namespace + ":act";
}
}
| {
"content_hash": "071ce7e8848c422bead066d20146c35a",
"timestamp": "",
"source": "github",
"line_count": 84,
"max_line_length": 79,
"avg_line_length": 31.61904761904762,
"alnum_prop": 0.5749246987951807,
"repo_name": "valterc/lings",
"id": "e1675387a32aaa94a641391a1b05dcbf4364caf6",
"size": "2658",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "LiNGSCommon/LiNGSMarkers.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "312746"
}
],
"symlink_target": ""
} |
package com.zhengxiaoyao0716.adapter;
import java.util.List;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
public class GuidePagerAdapter extends PagerAdapter{
//界面列表
private List<View> views;
public GuidePagerAdapter (List<View> views){
this.views = views;
}
//销毁arg1位置的界面
@Override
public void destroyItem(ViewGroup arg0, int arg1, Object arg2) {
arg0.removeView(views.get(arg1));
}
//获得当前界面数
@Override
public int getCount() {
if (views != null)
{
return views.size();
}
return 0;
}
//初始化arg1位置的界面
@Override
public Object instantiateItem(ViewGroup arg0, int arg1) {
arg0.addView(views.get(arg1), 0);
return views.get(arg1);
}
//判断是否由对象生成界面
@Override
public boolean isViewFromObject(View arg0, Object arg1) {
return (arg0 == arg1);
}
} | {
"content_hash": "f7a8600cb45c8cdf38130d5df2d2e5dc",
"timestamp": "",
"source": "github",
"line_count": 50,
"max_line_length": 68,
"avg_line_length": 19.38,
"alnum_prop": 0.6264189886480909,
"repo_name": "zhengxiaoyao0716/Digimon2048",
"id": "b46d3fd6e4db2e5417d96dda764071bc6e0ef31b",
"size": "1043",
"binary": false,
"copies": "1",
"ref": "refs/heads/zhengxiaoyao0716",
"path": "app/src/main/java/com/zhengxiaoyao0716/adapter/GuidePagerAdapter.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "52992"
}
],
"symlink_target": ""
} |
package org.apache.phoenix.exception;
import java.sql.SQLException;
import java.sql.SQLTimeoutException;
import java.util.Map;
import org.apache.phoenix.hbase.index.util.IndexManagementUtil;
import org.apache.phoenix.jdbc.PhoenixDatabaseMetaData;
import org.apache.phoenix.query.QueryServices;
import org.apache.phoenix.schema.AmbiguousColumnException;
import org.apache.phoenix.schema.AmbiguousTableException;
import org.apache.phoenix.schema.ColumnAlreadyExistsException;
import org.apache.phoenix.schema.ColumnFamilyNotFoundException;
import org.apache.phoenix.schema.ColumnNotFoundException;
import org.apache.phoenix.schema.ConcurrentTableMutationException;
import org.apache.phoenix.schema.FunctionAlreadyExistsException;
import org.apache.phoenix.schema.FunctionNotFoundException;
import org.apache.phoenix.schema.ReadOnlyTableException;
import org.apache.phoenix.schema.SequenceAlreadyExistsException;
import org.apache.phoenix.schema.SequenceNotFoundException;
import org.apache.phoenix.schema.StaleRegionBoundaryCacheException;
import org.apache.phoenix.schema.TableAlreadyExistsException;
import org.apache.phoenix.schema.TableNotFoundException;
import org.apache.phoenix.schema.TypeMismatchException;
import org.apache.phoenix.schema.types.PDataType;
import org.apache.phoenix.util.MetaDataUtil;
import com.google.common.collect.Maps;
/**
* Various SQLException Information. Including a vender-specific errorcode and a standard SQLState.
*
*
* @since 1.0
*/
public enum SQLExceptionCode {
/**
* Connection Exception (errorcode 01, sqlstate 08)
*/
IO_EXCEPTION(101, "08000", "Unexpected IO exception."),
MALFORMED_CONNECTION_URL(102, "08001", "Malformed connection url."),
CANNOT_ESTABLISH_CONNECTION(103, "08004", "Unable to establish connection."),
/**
* Data Exception (errorcode 02, sqlstate 22)
*/
ILLEGAL_DATA(201, "22000", "Illegal data."),
DIVIDE_BY_ZERO(202, "22012", "Divide by zero."),
TYPE_MISMATCH(203, "22005", "Type mismatch.", new Factory() {
@Override
public SQLException newException(SQLExceptionInfo info) {
return new TypeMismatchException(info.getMessage());
}
}),
VALUE_IN_UPSERT_NOT_CONSTANT(204, "22008", "Values in UPSERT must evaluate to a constant."),
MALFORMED_URL(205, "22009", "Malformed URL."),
DATA_EXCEEDS_MAX_CAPACITY(206, "22003", "The data exceeds the max capacity for the data type."),
MISSING_CHAR_LENGTH(207, "22003", "Missing length for CHAR."),
NONPOSITIVE_CHAR_LENGTH(208, "22003", "CHAR or VARCHAR must have a positive length."),
DECIMAL_PRECISION_OUT_OF_RANGE(209, "22003", "Decimal precision outside of range. Should be within 1 and " + PDataType.MAX_PRECISION + "."),
MISSING_BINARY_LENGTH(210, "22003", "Missing length for BINARY."),
NONPOSITIVE_BINARY_LENGTH(211, "22003", "BINARY must have a positive length."),
SERVER_ARITHMETIC_ERROR(212, "22012", "Arithmetic error on server."),
VALUE_OUTSIDE_RANGE(213,"22003","Value outside range."),
VALUE_IN_LIST_NOT_CONSTANT(214, "22008", "Values in IN must evaluate to a constant."),
SINGLE_ROW_SUBQUERY_RETURNS_MULTIPLE_ROWS(215, "22015", "Single-row sub-query returns more than one row."),
SUBQUERY_RETURNS_DIFFERENT_NUMBER_OF_FIELDS(216, "22016", "Sub-query must return the same number of fields as the left-hand-side expression of 'IN'."),
AMBIGUOUS_JOIN_CONDITION(217, "22017", "Amibiguous or non-equi join condition specified. Consider using table list with where clause."),
CONSTRAINT_VIOLATION(218, "22018", "Constraint violatioin."),
/**
* Constraint Violation (errorcode 03, sqlstate 23)
*/
CONCURRENT_TABLE_MUTATION(301, "23000", "Concurrent modification to table.", new Factory() {
@Override
public SQLException newException(SQLExceptionInfo info) {
return new ConcurrentTableMutationException(info.getSchemaName(), info.getTableName());
}
}),
CANNOT_INDEX_COLUMN_ON_TYPE(302, "23100", "The column cannot be index due to its type."),
/**
* Invalid Cursor State (errorcode 04, sqlstate 24)
*/
CURSOR_BEFORE_FIRST_ROW(401, "24015","Cursor before first row."),
CURSOR_PAST_LAST_ROW(402, "24016", "Cursor past last row."),
/**
* Syntax Error or Access Rule Violation (errorcode 05, sqlstate 42)
*/
AMBIGUOUS_TABLE(501, "42000", "Table name exists in more than one table schema and is used without being qualified.", new Factory() {
@Override
public SQLException newException(SQLExceptionInfo info) {
return new AmbiguousTableException(info.getTableName(), info.getRootCause());
}
}),
AMBIGUOUS_COLUMN(502, "42702", "Column reference ambiguous or duplicate names.", new Factory() {
@Override
public SQLException newException(SQLExceptionInfo info) {
return new AmbiguousColumnException(info.getColumnName(), info.getRootCause());
}
}),
INDEX_MISSING_PK_COLUMNS(503, "42602", "Index table missing PK Columns."),
COLUMN_NOT_FOUND(504, "42703", "Undefined column.", new Factory() {
@Override
public SQLException newException(SQLExceptionInfo info) {
return new ColumnNotFoundException(info.getSchemaName(), info.getTableName(), info.getFamilyName(), info.getColumnName());
}
}),
READ_ONLY_TABLE(505, "42000", "Table is read only.", new Factory() {
@Override
public SQLException newException(SQLExceptionInfo info) {
return new ReadOnlyTableException(info.getMessage(), info.getSchemaName(), info.getTableName(), info.getFamilyName());
}
}),
CANNOT_DROP_PK(506, "42817", "Primary key column may not be dropped."),
PRIMARY_KEY_MISSING(509, "42888", "The table does not have a primary key."),
PRIMARY_KEY_ALREADY_EXISTS(510, "42889", "The table already has a primary key."),
ORDER_BY_NOT_IN_SELECT_DISTINCT(511, "42890", "All ORDER BY expressions must appear in SELECT DISTINCT:"),
INVALID_PRIMARY_KEY_CONSTRAINT(512, "42891", "Invalid column reference in primary key constraint"),
ARRAY_NOT_ALLOWED_IN_PRIMARY_KEY(513, "42892", "Array type not allowed as primary key constraint"),
COLUMN_EXIST_IN_DEF(514, "42892", "A duplicate column name was detected in the object definition or ALTER TABLE statement.", new Factory() {
@Override
public SQLException newException(SQLExceptionInfo info) {
return new ColumnAlreadyExistsException(info.getSchemaName(), info.getTableName(), info.getColumnName());
}
}),
ORDER_BY_ARRAY_NOT_SUPPORTED(515, "42893", "ORDER BY of an array type is not allowed"),
NON_EQUALITY_ARRAY_COMPARISON(516, "42894", "Array types may only be compared using = or !="),
INVALID_NOT_NULL_CONSTRAINT(517, "42895", "Invalid not null constraint on non primary key column"),
/**
* Invalid Transaction State (errorcode 05, sqlstate 25)
*/
READ_ONLY_CONNECTION(518,"25502","Mutations are not permitted for a read-only connection."),
VARBINARY_ARRAY_NOT_SUPPORTED(519, "42896", "VARBINARY ARRAY is not supported"),
/**
* Expression Index exceptions.
*/
AGGREGATE_EXPRESSION_NOT_ALLOWED_IN_INDEX(520, "42897", "Aggreagaate expression not allowed in an index"),
NON_DETERMINISTIC_EXPRESSION_NOT_ALLOWED_IN_INDEX(521, "42898", "Non-deterministic expression not allowed in an index"),
STATELESS_EXPRESSION_NOT_ALLOWED_IN_INDEX(522, "42899", "Stateless expression not allowed in an index"),
/**
* Union All related errors
*/
SELECT_COLUMN_NUM_IN_UNIONALL_DIFFS(525, "42902", "SELECT column number differs in a Union All query is not allowed"),
SELECT_COLUMN_TYPE_IN_UNIONALL_DIFFS(526, "42903", "SELECT column types differ in a Union All query is not allowed"),
/**
* HBase and Phoenix specific implementation defined sub-classes.
* Column family related exceptions.
*
* For the following exceptions, use errorcode 10.
*/
SINGLE_PK_MAY_NOT_BE_NULL(1000, "42I00", "Single column primary key may not be NULL."),
COLUMN_FAMILY_NOT_FOUND(1001, "42I01", "Undefined column family.", new Factory() {
@Override
public SQLException newException(SQLExceptionInfo info) {
return new ColumnFamilyNotFoundException(info.getFamilyName());
}
}),
PROPERTIES_FOR_FAMILY(1002, "42I02","Properties may not be defined for an unused family name."),
// Primary/row key related exceptions.
PRIMARY_KEY_WITH_FAMILY_NAME(1003, "42J01", "Primary key columns must not have a family name."),
PRIMARY_KEY_OUT_OF_ORDER(1004, "42J02", "Order of columns in primary key constraint must match the order in which they're declared."),
VARBINARY_IN_ROW_KEY(1005, "42J03", "The VARBINARY/ARRAY type can only be used as the last part of a multi-part row key."),
NOT_NULLABLE_COLUMN_IN_ROW_KEY(1006, "42J04", "Only nullable columns may be added to a multi-part row key."),
VARBINARY_LAST_PK(1015, "42J04", "Cannot add column to table when the last PK column is of type VARBINARY or ARRAY."),
NULLABLE_FIXED_WIDTH_LAST_PK(1023, "42J04", "Cannot add column to table when the last PK column is nullable and fixed width."),
CANNOT_MODIFY_VIEW_PK(1036, "42J04", "Cannot modify the primary key of a VIEW."),
BASE_TABLE_COLUMN(1037, "42J04", "Cannot modify columns of base table used by tenant-specific tables."),
// Key/value column related errors
KEY_VALUE_NOT_NULL(1007, "42K01", "A key/value column may not be declared as not null."),
// View related errors.
VIEW_WITH_TABLE_CONFIG(1008, "42L01", "A view may not contain table configuration properties."),
VIEW_WITH_PROPERTIES(1009, "42L02", "Properties may not be defined for a view."),
// Table related errors that are not in standard code.
CANNOT_MUTATE_TABLE(1010, "42M01", "Not allowed to mutate table."),
UNEXPECTED_MUTATION_CODE(1011, "42M02", "Unexpected mutation code."),
TABLE_UNDEFINED(1012, "42M03", "Table undefined.", new Factory() {
@Override
public SQLException newException(SQLExceptionInfo info) {
return new TableNotFoundException(info.getSchemaName(), info.getTableName());
}
}),
TABLE_ALREADY_EXIST(1013, "42M04", "Table already exists.", new Factory() {
@Override
public SQLException newException(SQLExceptionInfo info) {
return new TableAlreadyExistsException(info.getSchemaName(), info.getTableName());
}
}),
// Syntax error
TYPE_NOT_SUPPORTED_FOR_OPERATOR(1014, "42Y01", "The operator does not support the operand type."),
AGGREGATE_IN_GROUP_BY(1016, "42Y26", "Aggregate expressions may not be used in GROUP BY."),
AGGREGATE_IN_WHERE(1017, "42Y26", "Aggregate may not be used in WHERE."),
AGGREGATE_WITH_NOT_GROUP_BY_COLUMN(1018, "42Y27", "Aggregate may not contain columns not in GROUP BY."),
ONLY_AGGREGATE_IN_HAVING_CLAUSE(1019, "42Y26", "Only aggregate maybe used in the HAVING clause."),
UPSERT_COLUMN_NUMBERS_MISMATCH(1020, "42Y60", "Number of columns upserting must match number of values."),
// Table properties exception.
INVALID_BUCKET_NUM(1021, "42Y80", "Salt bucket numbers should be with 1 and 256."),
NO_SPLITS_ON_SALTED_TABLE(1022, "42Y81", "Should not specify split points on salted table with default row key order."),
SALT_ONLY_ON_CREATE_TABLE(1024, "42Y82", "Salt bucket number may only be specified when creating a table."),
SET_UNSUPPORTED_PROP_ON_ALTER_TABLE(1025, "42Y83", "Unsupported property set in ALTER TABLE command."),
CANNOT_ADD_NOT_NULLABLE_COLUMN(1038, "42Y84", "Only nullable columns may be added for a pre-existing table."),
NO_MUTABLE_INDEXES(1026, "42Y85", "Mutable secondary indexes are only supported for HBase version " + MetaDataUtil.decodeHBaseVersionAsString(PhoenixDatabaseMetaData.MUTABLE_SI_VERSION_THRESHOLD) + " and above."),
INVALID_FILTER_ON_IMMUTABLE_ROWS(1027, "42Y86", "All columns referenced in a WHERE clause must be available in every index for a table with immutable rows."),
INVALID_INDEX_STATE_TRANSITION(1028, "42Y87", "Invalid index state transition."),
INVALID_MUTABLE_INDEX_CONFIG(1029, "42Y88", "Mutable secondary indexes must have the "
+ IndexManagementUtil.WAL_EDIT_CODEC_CLASS_KEY + " property set to "
+ IndexManagementUtil.INDEX_WAL_EDIT_CODEC_CLASS_NAME + " in the hbase-sites.xml of every region server"),
CANNOT_CREATE_TENANT_SPECIFIC_TABLE(1030, "42Y89", "Cannot create table for tenant-specific connection"),
CANNOT_DEFINE_PK_FOR_VIEW(1031, "42Y90", "Defining PK columns for a VIEW is not allowed."),
DEFAULT_COLUMN_FAMILY_ONLY_ON_CREATE_TABLE(1034, "42Y93", "Default column family may only be specified when creating a table."),
INSUFFICIENT_MULTI_TENANT_COLUMNS(1040, "42Y96", "A MULTI_TENANT table must have two or more PK columns with the first column being NOT NULL and of type VARCHAR or CHAR."),
VIEW_WHERE_IS_CONSTANT(1045, "43A02", "WHERE clause in VIEW should not evaluate to a constant."),
CANNOT_UPDATE_VIEW_COLUMN(1046, "43A03", "Column updated in VIEW may not differ from value specified in WHERE clause."),
TOO_MANY_INDEXES(1047, "43A04", "Too many indexes have already been created on the physical table."),
NO_LOCAL_INDEX_ON_TABLE_WITH_IMMUTABLE_ROWS(1048,"43A05","Local indexes aren't allowed on tables with immutable rows."),
COLUMN_FAMILY_NOT_ALLOWED_TABLE_PROPERTY(1049, "43A06", "Column family not allowed for table properties."),
COLUMN_FAMILY_NOT_ALLOWED_FOR_TTL(1050, "43A07", "Setting TTL for a column family not supported. You can only have TTL for the entire table."),
CANNOT_ALTER_PROPERTY(1051, "43A08", "Property can be specified or changed only when creating a table"),
CANNOT_SET_PROPERTY_FOR_COLUMN_NOT_ADDED(1052, "43A09", "Property cannot be specified for a column family that is not being added or modified"),
CANNOT_SET_TABLE_PROPERTY_ADD_COLUMN(1053, "43A10", "Table level property cannot be set when adding a column"),
NO_LOCAL_INDEXES(1054, "43A11", "Local secondary indexes are not supported for HBase versions " +
MetaDataUtil.decodeHBaseVersionAsString(PhoenixDatabaseMetaData.MIN_LOCAL_SI_VERSION_DISALLOW) + " through " + MetaDataUtil.decodeHBaseVersionAsString(PhoenixDatabaseMetaData.MAX_LOCAL_SI_VERSION_DISALLOW) + " inclusive."),
UNALLOWED_LOCAL_INDEXES(1055, "43A12", "Local secondary indexes are configured to not be allowed."),
/** Sequence related */
SEQUENCE_ALREADY_EXIST(1200, "42Z00", "Sequence already exists.", new Factory() {
@Override
public SQLException newException(SQLExceptionInfo info) {
return new SequenceAlreadyExistsException(info.getSchemaName(), info.getTableName());
}
}),
SEQUENCE_UNDEFINED(1201, "42Z01", "Sequence undefined.", new Factory() {
@Override
public SQLException newException(SQLExceptionInfo info) {
return new SequenceNotFoundException(info.getSchemaName(), info.getTableName());
}
}),
START_WITH_MUST_BE_CONSTANT(1202, "42Z02", "Sequence START WITH value must be an integer or long constant."),
INCREMENT_BY_MUST_BE_CONSTANT(1203, "42Z03", "Sequence INCREMENT BY value must be an integer or long constant."),
CACHE_MUST_BE_NON_NEGATIVE_CONSTANT(1204, "42Z04", "Sequence CACHE value must be a non negative integer constant."),
INVALID_USE_OF_NEXT_VALUE_FOR(1205, "42Z05", "NEXT VALUE FOR may only be used as in a SELECT or an UPSERT VALUES expression."),
CANNOT_CALL_CURRENT_BEFORE_NEXT_VALUE(1206, "42Z06", "NEXT VALUE FOR must be called before CURRENT VALUE FOR is called."),
EMPTY_SEQUENCE_CACHE(1207, "42Z07", "No more cached sequence values"),
MINVALUE_MUST_BE_CONSTANT(1208, "42Z08", "Sequence MINVALUE must be an integer or long constant."),
MAXVALUE_MUST_BE_CONSTANT(1209, "42Z09", "Sequence MAXVALUE must be an integer or long constant."),
MINVALUE_MUST_BE_LESS_THAN_OR_EQUAL_TO_MAXVALUE(1210, "42Z10", "Sequence MINVALUE must be less than or equal to MAXVALUE."),
STARTS_WITH_MUST_BE_BETWEEN_MIN_MAX_VALUE(1211, "42Z11",
"STARTS WITH value must be greater than or equal to MINVALUE and less than or equal to MAXVALUE"),
SEQUENCE_VAL_REACHED_MAX_VALUE(1212, "42Z12", "Reached MAXVALUE of sequence"),
SEQUENCE_VAL_REACHED_MIN_VALUE(1213, "42Z13", "Reached MINVALUE of sequence"),
INCREMENT_BY_MUST_NOT_BE_ZERO(1214, "42Z14", "Sequence INCREMENT BY value cannot be zero"),
/** Parser error. (errorcode 06, sqlState 42P) */
PARSER_ERROR(601, "42P00", "Syntax error.", Factory.SYTAX_ERROR),
MISSING_TOKEN(602, "42P00", "Syntax error.", Factory.SYTAX_ERROR),
UNWANTED_TOKEN(603, "42P00", "Syntax error.", Factory.SYTAX_ERROR),
MISMATCHED_TOKEN(604, "42P00", "Syntax error.", Factory.SYTAX_ERROR),
UNKNOWN_FUNCTION(605, "42P00", "Syntax error.", Factory.SYTAX_ERROR),
/**
* Implementation defined class. Execution exceptions (errorcode 11, sqlstate XCL).
*/
RESULTSET_CLOSED(1101, "XCL01", "ResultSet is closed."),
GET_TABLE_REGIONS_FAIL(1102, "XCL02", "Cannot get all table regions"),
EXECUTE_QUERY_NOT_APPLICABLE(1103, "XCL03", "executeQuery may not be used."),
EXECUTE_UPDATE_NOT_APPLICABLE(1104, "XCL04", "executeUpdate may not be used."),
SPLIT_POINT_NOT_CONSTANT(1105, "XCL05", "Split points must be constants."),
BATCH_EXCEPTION(1106, "XCL06", "Exception while executing batch."),
EXECUTE_UPDATE_WITH_NON_EMPTY_BATCH(1107, "XCL07", "An executeUpdate is prohibited when the batch is not empty. Use clearBatch to empty the batch first."),
STALE_REGION_BOUNDARY_CACHE(1108, "XCL08", "Cache of region boundaries are out of date.", new Factory() {
@Override
public SQLException newException(SQLExceptionInfo info) {
return new StaleRegionBoundaryCacheException(info.getSchemaName(), info.getTableName());
}
}),
CANNOT_SPLIT_LOCAL_INDEX(1109,"XCL09", "Local index may not be pre-split"),
CANNOT_SALT_LOCAL_INDEX(1110,"XCL10", "Local index may not be salted"),
/**
* Implementation defined class. Phoenix internal error. (errorcode 20, sqlstate INT).
*/
CANNOT_CALL_METHOD_ON_TYPE(2001, "INT01", "Cannot call method on the argument type."),
CLASS_NOT_UNWRAPPABLE(2002, "INT03", "Class not unwrappable"),
PARAM_INDEX_OUT_OF_BOUND(2003, "INT04", "Parameter position is out of range."),
PARAM_VALUE_UNBOUND(2004, "INT05", "Parameter value unbound"),
INTERRUPTED_EXCEPTION(2005, "INT07", "Interrupted exception."),
INCOMPATIBLE_CLIENT_SERVER_JAR(2006, "INT08", "Incompatible jars detected between client and server."),
OUTDATED_JARS(2007, "INT09", "Outdated jars."),
INDEX_METADATA_NOT_FOUND(2008, "INT10", "Unable to find cached index metadata. "),
UNKNOWN_ERROR_CODE(2009, "INT11", "Unknown error code"),
OPERATION_TIMED_OUT(6000, "TIM01", "Operation timed out", new Factory() {
@Override
public SQLException newException(SQLExceptionInfo info) {
return new SQLTimeoutException(OPERATION_TIMED_OUT.getMessage(),
OPERATION_TIMED_OUT.getSQLState(), OPERATION_TIMED_OUT.getErrorCode());
}
}),
FUNCTION_UNDEFINED(6001, "42F01", "Function undefined.", new Factory() {
@Override
public SQLException newException(SQLExceptionInfo info) {
return new FunctionNotFoundException(info.getFunctionName());
}
}),
FUNCTION_ALREADY_EXIST(6002, "42F02", "Function already exists.", new Factory() {
@Override
public SQLException newException(SQLExceptionInfo info) {
return new FunctionAlreadyExistsException(info.getSchemaName(), info.getTableName());
}
}),
UNALLOWED_USER_DEFINED_FUNCTIONS(6003, "42F03",
"User defined functions are configured to not be allowed. To allow configure "
+ QueryServices.ALLOW_USER_DEFINED_FUNCTIONS_ATTRIB + " to true."),
;
private final int errorCode;
private final String sqlState;
private final String message;
private final Factory factory;
private SQLExceptionCode(int errorCode, String sqlState, String message) {
this(errorCode, sqlState, message, Factory.DEFAULTY);
}
private SQLExceptionCode(int errorCode, String sqlState, String message, Factory factory) {
this.errorCode = errorCode;
this.sqlState = sqlState;
this.message = message;
this.factory = factory;
}
public String getSQLState() {
return sqlState;
}
public String getMessage() {
return message;
}
public int getErrorCode() {
return errorCode;
}
@Override
public String toString() {
return "ERROR " + errorCode + " (" + sqlState + "): " + message;
}
public Factory getExceptionFactory() {
return factory;
}
public static interface Factory {
public static final Factory DEFAULTY = new Factory() {
@Override
public SQLException newException(SQLExceptionInfo info) {
return new SQLException(info.toString(), info.getCode().getSQLState(), info.getCode().getErrorCode(), info.getRootCause());
}
};
public static final Factory SYTAX_ERROR = new Factory() {
@Override
public SQLException newException(SQLExceptionInfo info) {
return new PhoenixParserException(info.getMessage(), info.getRootCause());
}
};
public SQLException newException(SQLExceptionInfo info);
}
private static final Map<Integer,SQLExceptionCode> errorCodeMap = Maps.newHashMapWithExpectedSize(SQLExceptionCode.values().length);
static {
for (SQLExceptionCode code : SQLExceptionCode.values()) {
SQLExceptionCode otherCode = errorCodeMap.put(code.getErrorCode(), code);
if (otherCode != null) {
throw new IllegalStateException("Duplicate error code for " + code + " and " + otherCode);
}
}
}
public static SQLExceptionCode fromErrorCode(int errorCode) throws SQLException {
SQLExceptionCode code = errorCodeMap.get(errorCode);
if (code == null) {
throw new SQLExceptionInfo.Builder(SQLExceptionCode.UNKNOWN_ERROR_CODE)
.setMessage(Integer.toString(errorCode)).build().buildException();
}
return code;
}
}
| {
"content_hash": "ce736801f0d7cc6a0e5124441d3f2193",
"timestamp": "",
"source": "github",
"line_count": 403,
"max_line_length": 231,
"avg_line_length": 56.526054590570716,
"alnum_prop": 0.6959174714661984,
"repo_name": "codymarcel/phoenix",
"id": "cf723843c8c67165d345a43632f24d71ed6eb86b",
"size": "23581",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "phoenix-core/src/main/java/org/apache/phoenix/exception/SQLExceptionCode.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "GAP",
"bytes": "43799"
},
{
"name": "HTML",
"bytes": "1865"
},
{
"name": "Java",
"bytes": "10298362"
},
{
"name": "PigLatin",
"bytes": "210"
},
{
"name": "Protocol Buffer",
"bytes": "12917"
},
{
"name": "Python",
"bytes": "60660"
},
{
"name": "Scala",
"bytes": "42162"
},
{
"name": "Shell",
"bytes": "57375"
}
],
"symlink_target": ""
} |
package gov.va.med.lom.javaBroker.rpc.lists;
import java.util.ArrayList;
import gov.va.med.lom.javaBroker.rpc.*;
import gov.va.med.lom.javaBroker.rpc.lists.models.*;
import gov.va.med.lom.javaBroker.util.StringUtils;
public class OrderItemsRpc extends AbstractRpc {
// FIELDS
private OrderItemsList orderItemsList;
// CONSTRUCTORS
public OrderItemsRpc() throws BrokerException {
super();
}
public OrderItemsRpc(RpcBroker rpcBroker) throws BrokerException {
super(rpcBroker);
}
// RPC API
public synchronized OrderItemsList getSubSetOfOrderItems(String startFrom, int direction, String xRef) throws BrokerException {
if (setContext("OR CPRS GUI CHART")) {
String[] params = {startFrom, String.valueOf(direction), xRef};
ArrayList list = lCall("ORWDX ORDITM", params);
orderItemsList = getItems(list, false);
return orderItemsList;
} else
throw getCreateContextException("OR CPRS GUI CHART");
}
// Parses the result list from VistA and returns array of patient list item objects
private OrderItemsList getItems(ArrayList list, boolean mixedCase) {
orderItemsList = new OrderItemsList();
if (returnRpcResult) {
StringBuffer sb = new StringBuffer();
for(int i = 0; i < list.size(); i++)
sb.append((String)list.get(i) + "\n");
orderItemsList.setRpcResult(sb.toString().trim());
}
OrderItem[] orderItems = new OrderItem[list.size()];
for(int i=0; i < list.size(); i++) {
OrderItem orderItem = new OrderItem();
String x = (String)list.get(i);
if (returnRpcResult)
orderItem.setRpcResult(x);
String ien = StringUtils.piece(x, 1);
String name;
if (mixedCase)
name = StringUtils.mixedCase(StringUtils.piece(x, 2));
else
name = StringUtils.piece(x, 2);
orderItem.setIen(ien);
orderItem.setName(name);
orderItems[i] = orderItem;
}
orderItemsList.setOrderItems(orderItems);
return orderItemsList;
}
}
| {
"content_hash": "29e1634f803553547627fde606e0d862",
"timestamp": "",
"source": "github",
"line_count": 62,
"max_line_length": 129,
"avg_line_length": 33.774193548387096,
"alnum_prop": 0.6537726838586437,
"repo_name": "VHAINNOVATIONS/AVS",
"id": "93029a23c1e38fcb5d434d43565c40a7342110b5",
"size": "2094",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ll-javaBroker/src/main/java/gov/va/med/lom/javaBroker/rpc/lists/OrderItemsRpc.java",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "97314"
},
{
"name": "Elixir",
"bytes": "758"
},
{
"name": "Java",
"bytes": "3765290"
},
{
"name": "JavaScript",
"bytes": "5395171"
},
{
"name": "Pascal",
"bytes": "17829"
},
{
"name": "Shell",
"bytes": "10984"
}
],
"symlink_target": ""
} |
from concurrent.futures import ProcessPoolExecutor
from functools import partial
import numpy as np
import os
from hparams import hparams
from util import audio
_max_out_length = 700
_end_buffer = 0.05
_min_confidence = 90
# Note: "A Tramp Abroad" & "The Man That Corrupted Hadleyburg" are higher quality than the others.
books = [
'ATrampAbroad',
'TheManThatCorruptedHadleyburg',
# 'LifeOnTheMississippi',
# 'TheAdventuresOfTomSawyer',
]
def build_from_path(in_dir, out_dir, num_workers=1, tqdm=lambda x: x):
executor = ProcessPoolExecutor(max_workers=num_workers)
futures = []
index = 1
for book in books:
with open(os.path.join(in_dir, book, 'sentence_index.txt')) as f:
for line in f:
parts = line.strip().split('\t')
if line[0] is not '#' and len(parts) == 8 and float(parts[3]) > _min_confidence:
wav_path = os.path.join(in_dir, book, 'wav', '%s.wav' % parts[0])
labels_path = os.path.join(in_dir, book, 'lab', '%s.lab' % parts[0])
text = parts[5]
task = partial(_process_utterance, out_dir, index, wav_path, labels_path, text)
futures.append(executor.submit(task))
index += 1
results = [future.result() for future in tqdm(futures)]
return [r for r in results if r is not None]
def _process_utterance(out_dir, index, wav_path, labels_path, text):
# Load the wav file and trim silence from the ends:
wav = audio.load_wav(wav_path)
start_offset, end_offset = _parse_labels(labels_path)
start = int(start_offset * hparams.sample_rate)
end = int(end_offset * hparams.sample_rate) if end_offset is not None else -1
wav = wav[start:end]
max_samples = _max_out_length * hparams.frame_shift_ms / 1000 * hparams.sample_rate
if len(wav) > max_samples:
return None
spectrogram = audio.spectrogram(wav).astype(np.float32)
n_frames = spectrogram.shape[1]
mel_spectrogram = audio.melspectrogram(wav).astype(np.float32)
spectrogram_filename = 'blizzard-spec-%05d.npy' % index
mel_filename = 'blizzard-mel-%05d.npy' % index
np.save(os.path.join(out_dir, spectrogram_filename), spectrogram.T, allow_pickle=False)
np.save(os.path.join(out_dir, mel_filename), mel_spectrogram.T, allow_pickle=False)
return (spectrogram_filename, mel_filename, n_frames, text)
def _parse_labels(path):
labels = []
with open(os.path.join(path)) as f:
for line in f:
parts = line.strip().split(' ')
if len(parts) >= 3:
labels.append((float(parts[0]), ' '.join(parts[2:])))
start = 0
end = None
if labels[0][1] == 'sil':
start = labels[0][0]
if labels[-1][1] == 'sil':
end = labels[-2][0] + _end_buffer
return (start, end)
| {
"content_hash": "61d55b51c25a8e5d00a39c42acf0f7f8",
"timestamp": "",
"source": "github",
"line_count": 73,
"max_line_length": 98,
"avg_line_length": 36.78082191780822,
"alnum_prop": 0.6659217877094972,
"repo_name": "tosaka2/tacotron",
"id": "eddd86da805c3e18c506e6cf40e420ab7ecb38f9",
"size": "2685",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "datasets/blizzard.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "52537"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
android:id="@+id/tv01"
android:textSize="36sp"
/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="输入账号"
android:id="@+id/btn01"
/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="图片剪切"
android:id="@+id/btn02"
/>
</LinearLayout>
| {
"content_hash": "7804ad8e17234b13cbc468cb080c439a",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 72,
"avg_line_length": 28.346153846153847,
"alnum_prop": 0.6635006784260515,
"repo_name": "shengge/eoe-Libraries-for-Android-Developers",
"id": "ab457a59cd0f5e08ac815b94121741a9cb89ef6d",
"size": "753",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "bundles/ActivityForResultDemo/res/layout/main.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "1593727"
}
],
"symlink_target": ""
} |
package com.datastax.driver.core;
import java.util.Collection;
import java.util.List;
import com.google.common.base.Objects;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.Test;
import static org.assertj.core.api.Assertions.assertThat;
import com.datastax.driver.core.policies.DelegatingLoadBalancingPolicy;
import com.datastax.driver.core.policies.LoadBalancingPolicy;
import com.datastax.driver.core.policies.RoundRobinPolicy;
import static com.datastax.driver.core.LoadBalancingPolicyBootstrapTest.HistoryPolicy.Action.*;
import static com.datastax.driver.core.LoadBalancingPolicyBootstrapTest.HistoryPolicy.entry;
public class LoadBalancingPolicyBootstrapTest {
private static final Logger logger = LoggerFactory.getLogger(LoadBalancingPolicyBootstrapTest.class);
/**
* Ensures that when a cluster is initialized that {@link LoadBalancingPolicy#init(Cluster, Collection)} is called
* with each reachable contact point.
*
* @test_category load_balancing:notification
* @expected_result init() is called for each of two contact points.
*/
@Test(groups = "short")
public void should_init_policy_with_up_contact_points() throws Exception {
HistoryPolicy policy = new HistoryPolicy(new RoundRobinPolicy());
CCMBridge ccm = null;
Cluster cluster = null;
try {
ccm = CCMBridge.create("test", 2);
cluster = Cluster.builder()
.addContactPoints(CCMBridge.ipOfNode(1), CCMBridge.ipOfNode(2))
.withLoadBalancingPolicy(policy)
.build();
cluster.init();
assertThat(policy.history).containsOnly(
entry(INIT, TestUtils.findHost(cluster, 1)),
entry(INIT, TestUtils.findHost(cluster, 2))
);
} finally {
if (cluster != null)
cluster.close();
if (ccm != null)
ccm.remove();
}
}
/**
* Ensures that {@link LoadBalancingPolicy#onDown(Host)} is called for a contact point that couldn't
* be reached while initializing the control connection, but only after
* {@link LoadBalancingPolicy#init(Cluster, Collection)} has been called.
*
* @test_category load_balancing:notification
* @expected_result init() is called with the up host, followed by onDown() for the downed host.
* @jira_ticket JAVA-613
* @since 2.0.10, 2.1.5
*/
@Test(groups = "short")
public void should_send_down_notifications_after_init_when_contact_points_are_down() throws Exception {
CCMBridge ccm = null;
Cluster cluster = null;
try {
ccm = CCMBridge.create("test", 2);
// In order to validate this behavior, we need to stop the first node that would be attempted to be
// established as the control connection.
// This depends on the internal behavior and will even be made totally random by JAVA-618, therefore
// we retry the scenario until we get the desired preconditions.
int nodeToStop = 1;
int tries = 1, maxTries = 10;
for (; tries <= maxTries; tries++) {
nodeToStop = (nodeToStop == 1) ? 2 : 1; // switch nodes at each try
int activeNode = nodeToStop == 2 ? 1 : 2;
ccm.stop(nodeToStop);
ccm.waitForDown(nodeToStop);
HistoryPolicy policy = new HistoryPolicy(new RoundRobinPolicy());
cluster = Cluster.builder()
.addContactPoints(CCMBridge.ipOfNode(1), CCMBridge.ipOfNode(2))
.withLoadBalancingPolicy(policy)
.build();
cluster.init();
if (policy.history.contains(entry(DOWN, TestUtils.findHost(cluster, nodeToStop)))) {
// This is the situation we're testing, the control connection tried the stopped node first.
assertThat(policy.history).containsExactly(
entry(INIT, TestUtils.findHost(cluster, activeNode)),
entry(DOWN, TestUtils.findHost(cluster, nodeToStop))
);
break;
} else {
assertThat(policy.history).containsOnly(
entry(INIT, TestUtils.findHost(cluster, 1)),
entry(INIT, TestUtils.findHost(cluster, 2))
);
logger.info("Could not get first contact point to fail, retrying");
cluster.close();
ccm.start(nodeToStop);
ccm.waitForUp(nodeToStop);
}
}
if (tries == maxTries + 1)
logger.warn("Could not get first contact point to fail after {} tries", maxTries);
} finally {
if (cluster != null)
cluster.close();
if (ccm != null)
ccm.remove();
}
}
static class HistoryPolicy extends DelegatingLoadBalancingPolicy {
enum Action {INIT, UP, DOWN, ADD, REMOVE, SUSPECT}
static class Entry {
final Action action;
final Host host;
public Entry(Action action, Host host) {
this.action = action;
this.host = host;
}
@Override
public boolean equals(Object other) {
if (other == this)
return true;
if (other instanceof Entry) {
Entry that = (Entry)other;
return this.action == that.action && this.host.equals(that.host);
}
return false;
}
@Override
public int hashCode() {
return Objects.hashCode(action, host);
}
@Override public String toString() {
return Objects.toStringHelper(this).add("action", action).add("host", host).toString();
}
}
static Entry entry(Action action, Host host) {
return new Entry(action, host);
}
List<Entry> history = Lists.newArrayList();
public HistoryPolicy(LoadBalancingPolicy delegate) {
super(delegate);
}
@Override
public void init(Cluster cluster, Collection<Host> hosts) {
super.init(cluster, hosts);
for (Host host : hosts) {
history.add(entry(INIT, host));
}
}
public void onAdd(Host host) {
history.add(entry(ADD, host));
super.onAdd(host);
}
public void onSuspected(Host host) {
history.add(entry(SUSPECT, host));
super.onSuspected(host);
}
public void onUp(Host host) {
history.add(entry(UP, host));
super.onUp(host);
}
public void onDown(Host host) {
history.add(entry(DOWN, host));
super.onDown(host);
}
public void onRemove(Host host) {
history.add(entry(REMOVE, host));
super.onRemove(host);
}
}
}
| {
"content_hash": "901900dc29a758b6881f0726d79cf1b9",
"timestamp": "",
"source": "github",
"line_count": 208,
"max_line_length": 118,
"avg_line_length": 35.18269230769231,
"alnum_prop": 0.5696911724514895,
"repo_name": "mashuai/Cassandra-Java-Driver-Research",
"id": "d6078febcdfa9085786120afabe1d27025cde77d",
"size": "7945",
"binary": false,
"copies": "6",
"ref": "refs/heads/2.1",
"path": "driver-core/src/test/java/com/datastax/driver/core/LoadBalancingPolicyBootstrapTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "2723061"
},
{
"name": "Python",
"bytes": "6866"
},
{
"name": "Shell",
"bytes": "1596"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_60-ea) on Mon Oct 03 10:36:48 EDT 2016 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Interface org.wildfly.swarm.config.management.security_realm.SecretServerIdentitySupplier (Public javadocs 2016.10.0 API)</title>
<meta name="date" content="2016-10-03">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Interface org.wildfly.swarm.config.management.security_realm.SecretServerIdentitySupplier (Public javadocs 2016.10.0 API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../org/wildfly/swarm/config/management/security_realm/SecretServerIdentitySupplier.html" title="interface in org.wildfly.swarm.config.management.security_realm">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">WildFly Swarm API, 2016.10.0</div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?org/wildfly/swarm/config/management/security_realm/class-use/SecretServerIdentitySupplier.html" target="_top">Frames</a></li>
<li><a href="SecretServerIdentitySupplier.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Interface org.wildfly.swarm.config.management.security_realm.SecretServerIdentitySupplier" class="title">Uses of Interface<br>org.wildfly.swarm.config.management.security_realm.SecretServerIdentitySupplier</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../../../org/wildfly/swarm/config/management/security_realm/SecretServerIdentitySupplier.html" title="interface in org.wildfly.swarm.config.management.security_realm">SecretServerIdentitySupplier</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#org.wildfly.swarm.config.management">org.wildfly.swarm.config.management</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="org.wildfly.swarm.config.management">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../../org/wildfly/swarm/config/management/security_realm/SecretServerIdentitySupplier.html" title="interface in org.wildfly.swarm.config.management.security_realm">SecretServerIdentitySupplier</a> in <a href="../../../../../../../org/wildfly/swarm/config/management/package-summary.html">org.wildfly.swarm.config.management</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../../org/wildfly/swarm/config/management/package-summary.html">org.wildfly.swarm.config.management</a> with parameters of type <a href="../../../../../../../org/wildfly/swarm/config/management/security_realm/SecretServerIdentitySupplier.html" title="interface in org.wildfly.swarm.config.management.security_realm">SecretServerIdentitySupplier</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../../org/wildfly/swarm/config/management/SecurityRealm.html" title="type parameter in SecurityRealm">T</a></code></td>
<td class="colLast"><span class="typeNameLabel">SecurityRealm.</span><code><span class="memberNameLink"><a href="../../../../../../../org/wildfly/swarm/config/management/SecurityRealm.html#secretServerIdentity-org.wildfly.swarm.config.management.security_realm.SecretServerIdentitySupplier-">secretServerIdentity</a></span>(<a href="../../../../../../../org/wildfly/swarm/config/management/security_realm/SecretServerIdentitySupplier.html" title="interface in org.wildfly.swarm.config.management.security_realm">SecretServerIdentitySupplier</a> supplier)</code>
<div class="block">Configuration of the secret/password-based identity of a server or host
controller.</div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../org/wildfly/swarm/config/management/security_realm/SecretServerIdentitySupplier.html" title="interface in org.wildfly.swarm.config.management.security_realm">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">WildFly Swarm API, 2016.10.0</div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?org/wildfly/swarm/config/management/security_realm/class-use/SecretServerIdentitySupplier.html" target="_top">Frames</a></li>
<li><a href="SecretServerIdentitySupplier.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2016 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p>
</body>
</html>
| {
"content_hash": "ee085d631c876bb4ea5f6bb23fbdb43f",
"timestamp": "",
"source": "github",
"line_count": 171,
"max_line_length": 566,
"avg_line_length": 48.058479532163744,
"alnum_prop": 0.661353127281577,
"repo_name": "wildfly-swarm/wildfly-swarm-javadocs",
"id": "31d853568eaced655271391dc1c96a636dde5641",
"size": "8218",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "2016.10.0/apidocs/org/wildfly/swarm/config/management/security_realm/class-use/SecretServerIdentitySupplier.html",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
/**
* DocuSign REST API
* The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign.
*
* OpenAPI spec version: v2.1
* Contact: devcenter@docusign.com
*
* NOTE: This class is auto generated. Do not edit the class manually and submit a new issue instead.
*
*/
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['ApiClient', 'model/FormDataItem', 'model/PrefillFormData', 'model/RecipientFormData'], factory);
} else if (typeof module === 'object' && module.exports) {
// CommonJS-like environments that support module.exports, like Node.
module.exports = factory(require('../ApiClient'), require('./FormDataItem'), require('./PrefillFormData'), require('./RecipientFormData'));
} else {
// Browser globals (root is window)
if (!root.Docusign) {
root.Docusign = {};
}
root.Docusign.EnvelopeFormData = factory(root.Docusign.ApiClient, root.Docusign.FormDataItem, root.Docusign.PrefillFormData, root.Docusign.RecipientFormData);
}
}(this, function(ApiClient, FormDataItem, PrefillFormData, RecipientFormData) {
'use strict';
/**
* The EnvelopeFormData model module.
* @module model/EnvelopeFormData
*/
/**
* Constructs a new <code>EnvelopeFormData</code>.
* @alias module:model/EnvelopeFormData
* @class
*/
var exports = function() {
var _this = this;
};
/**
* Constructs a <code>EnvelopeFormData</code> from a plain JavaScript object, optionally creating a new instance.
* Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
* @param {Object} data The plain JavaScript object bearing properties of interest.
* @param {module:model/EnvelopeFormData} obj Optional instance to populate.
* @return {module:model/EnvelopeFormData} The populated <code>EnvelopeFormData</code> instance.
*/
exports.constructFromObject = function(data, obj) {
if (data) {
obj = obj || new exports();
if (data.hasOwnProperty('emailSubject')) {
obj['emailSubject'] = ApiClient.convertToType(data['emailSubject'], 'String');
}
if (data.hasOwnProperty('envelopeId')) {
obj['envelopeId'] = ApiClient.convertToType(data['envelopeId'], 'String');
}
if (data.hasOwnProperty('formData')) {
obj['formData'] = ApiClient.convertToType(data['formData'], [FormDataItem]);
}
if (data.hasOwnProperty('prefillFormData')) {
obj['prefillFormData'] = PrefillFormData.constructFromObject(data['prefillFormData']);
}
if (data.hasOwnProperty('recipientFormData')) {
obj['recipientFormData'] = ApiClient.convertToType(data['recipientFormData'], [RecipientFormData]);
}
if (data.hasOwnProperty('sentDateTime')) {
obj['sentDateTime'] = ApiClient.convertToType(data['sentDateTime'], 'String');
}
if (data.hasOwnProperty('status')) {
obj['status'] = ApiClient.convertToType(data['status'], 'String');
}
}
return obj;
}
/**
* Specifies the subject of the email that is sent to all recipients. See [ML:Template Email Subject Merge Fields] for information about adding merge field information to the email subject.
* @member {String} emailSubject
*/
exports.prototype['emailSubject'] = undefined;
/**
* The envelope ID of the envelope status that failed to post.
* @member {String} envelopeId
*/
exports.prototype['envelopeId'] = undefined;
/**
*
* @member {Array.<module:model/FormDataItem>} formData
*/
exports.prototype['formData'] = undefined;
/**
* @member {module:model/PrefillFormData} prefillFormData
*/
exports.prototype['prefillFormData'] = undefined;
/**
*
* @member {Array.<module:model/RecipientFormData>} recipientFormData
*/
exports.prototype['recipientFormData'] = undefined;
/**
* The date and time the envelope was sent.
* @member {String} sentDateTime
*/
exports.prototype['sentDateTime'] = undefined;
/**
* Indicates the envelope status. Valid values are: * sent - The envelope is sent to the recipients. * created - The envelope is saved as a draft and can be modified and sent later.
* @member {String} status
*/
exports.prototype['status'] = undefined;
return exports;
}));
| {
"content_hash": "f849ac081b525a0b407e8505692afb3f",
"timestamp": "",
"source": "github",
"line_count": 122,
"max_line_length": 192,
"avg_line_length": 36.204918032786885,
"alnum_prop": 0.6780620330541092,
"repo_name": "docusign/docusign-node-client",
"id": "f49c2ac91ef5d499f53f45027062853ce5774a0d",
"size": "4417",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/model/EnvelopeFormData.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "4711737"
}
],
"symlink_target": ""
} |
class ClientCss < ActiveRecord::Migration
def self.up
add_column :customers, :css, :text
end
def self.down
remove_column :customers, :css
end
end
| {
"content_hash": "1883b3aca3cf38fd7b94deef26fdfc39",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 41,
"avg_line_length": 18.11111111111111,
"alnum_prop": 0.6932515337423313,
"repo_name": "claudiobm/ClockingIT-In-CapellaDesign",
"id": "15c48317ac289e23b1ff27001d4728ff806a217f",
"size": "163",
"binary": false,
"copies": "12",
"ref": "refs/heads/master",
"path": "db/migrate/008_client_css.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "535091"
},
{
"name": "PHP",
"bytes": "14202"
},
{
"name": "Ruby",
"bytes": "1346119"
}
],
"symlink_target": ""
} |
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "95ff27ebe46074e59a9eee5ab38a99b2",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.23076923076923,
"alnum_prop": 0.6917293233082706,
"repo_name": "mdoering/backbone",
"id": "3979d7a555434123f77937bc8665333f4de44009",
"size": "195",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Liliopsida/Liliales/Liliaceae/Fritillaria/Fritillaria verticillata/ Syn. Fritillaria albidiflora jimunaica/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
using System;
using System.Reflection;
using XGraph.ViewModels;
namespace XZoomAndPan.TestApp.Graph
{
/// <summary>
/// This view model represents a type.
/// </summary>
class TypeNodeViewModel : NodeViewModel
{
/// <summary>
/// Initializes a new instance of the <see cref="TypeNodeViewModel"/> class.
/// </summary>
/// <param name="pType">Type of the port.</param>
public TypeNodeViewModel(Type pType)
{
this.DisplayString = pType.Name;
this.Description = "A class sample node.";
foreach (PropertyInfo lPropertyInfo in pType.GetProperties())
{
if (lPropertyInfo.CanWrite)
{
PortViewModel lPort = null;
lPort = new PortViewModel {Direction = PortDirection.Input, DisplayString = lPropertyInfo.Name, PortType = "Property"};
this.Ports.Add(lPort);
}
if (lPropertyInfo.CanRead)
{
PortViewModel lPort = null;
lPort = new PortViewModel { Direction = PortDirection.Output, DisplayString = lPropertyInfo.Name, PortType = "Property" };
this.Ports.Add(lPort);
}
}
foreach (EventInfo lEventInfo in pType.GetEvents())
{
PortViewModel lPort = new PortViewModel {Direction = PortDirection.Output, PortType = "Event", DisplayString = lEventInfo.Name};
this.Ports.Add(lPort);
}
}
}
}
| {
"content_hash": "8966bea6a6c9e307d8bdc67eb48cbd2c",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 144,
"avg_line_length": 36.08888888888889,
"alnum_prop": 0.541256157635468,
"repo_name": "mastertnt/XRay",
"id": "897a1f5b4838a2c7986c21515287c0bd0f5de961",
"size": "1626",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "XZoomAndPan.TestApp/Graph/TypeNodeViewModel.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "1634341"
}
],
"symlink_target": ""
} |
import homepageHeaderTemplate from './views/header/index.html'
import backgroundTemplate from './views/home/index.html'
import aboutSectionTemplate from './views/about/index.html'
import workSectionTemplate from './views/work/index.html'
import '../index.scss'
import './views/home/styles.scss'
import './views/header/styles.scss'
import './views/about/styles.scss'
import './views/work/styles.scss'
(() => {
window.onunload = function () {
window.scrollTo(0, 0);
}
const appContainer = document.getElementById('app');
appContainer.insertAdjacentHTML('beforeend', homepageHeaderTemplate);
appContainer.insertAdjacentHTML('beforeend', backgroundTemplate);
appContainer.insertAdjacentHTML('beforeend', aboutSectionTemplate);
appContainer.insertAdjacentHTML('beforeend', workSectionTemplate);
})();
| {
"content_hash": "75abf85f92422d36de4a72a0785c6eb5",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 73,
"avg_line_length": 38.13636363636363,
"alnum_prop": 0.7473182359952324,
"repo_name": "karanaditya993/karanaditya993.github.io",
"id": "7b90d222f1e4c9e535a58b1d85c4dc5789b0c859",
"size": "839",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/index.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "4627"
},
{
"name": "HTML",
"bytes": "48044"
}
],
"symlink_target": ""
} |
// Generated from /POI/java/org/apache/poi/ss/usermodel/TableStyleType.java
#pragma once
#include <java/lang/fwd-POI.hpp>
#include <org/apache/poi/ss/usermodel/fwd-POI.hpp>
#include <org/apache/poi/ss/util/fwd-POI.hpp>
#include <org/apache/poi/ss/usermodel/TableStyleType.hpp>
struct default_init_tag;
class poi::ss::usermodel::TableStyleType_5 final
: public TableStyleType
{
public:
typedef TableStyleType super;
public: /* package */
::poi::ss::util::CellRangeAddressBase* getRange(Table* table, Cell* cell) override;
// Generated
public:
TableStyleType_5(::java::lang::String* name, int ordinal);
static ::java::lang::Class *class_();
private:
virtual ::java::lang::Class* getClass0();
friend class TableStyleType;
friend class TableStyleType_1;
friend class TableStyleType_2;
friend class TableStyleType_3;
friend class TableStyleType_4;
friend class TableStyleType_6;
friend class TableStyleType_7;
friend class TableStyleType_8;
friend class TableStyleType_9;
friend class TableStyleType_10;
friend class TableStyleType_11;
friend class TableStyleType_12;
friend class TableStyleType_13;
};
| {
"content_hash": "de77b9e136dcc033557576b659efb047",
"timestamp": "",
"source": "github",
"line_count": 43,
"max_line_length": 87,
"avg_line_length": 27.6046511627907,
"alnum_prop": 0.7253580454928391,
"repo_name": "pebble2015/cpoi",
"id": "f90742e732375b717275a6df997221b846e9cfc1",
"size": "1187",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/org/apache/poi/ss/usermodel/TableStyleType_5.hpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C++",
"bytes": "15964112"
},
{
"name": "Makefile",
"bytes": "138107"
}
],
"symlink_target": ""
} |
<readable><title>2524003134_580e74328b</title><content>
A brown and white dog , wearing a collar , is moving through some water .
A brown and white dog with a collar wading in a river .
A dog is in the water .
A dog standing in water .
A dog swims through the water .
</content></readable> | {
"content_hash": "7db8193ca3bd27919a0d90fcf1f61258",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 73,
"avg_line_length": 41.285714285714285,
"alnum_prop": 0.7474048442906575,
"repo_name": "kevint2u/audio-collector",
"id": "cbeb631fb2be168fc32811fccc1955ffd3446d50",
"size": "289",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "captions/xml/2524003134_580e74328b.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1015"
},
{
"name": "HTML",
"bytes": "18349"
},
{
"name": "JavaScript",
"bytes": "109819"
},
{
"name": "Python",
"bytes": "3260"
},
{
"name": "Shell",
"bytes": "4319"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RandomTests.Data.Infrastructure
{
public class DbFactory : Disposable, IDbFactory
{
RandomTestsContext dbContext;
public RandomTestsContext Init()
{
return dbContext ?? (dbContext = new RandomTestsContext());
}
protected override void DisposeCore()
{
if (dbContext != null)
dbContext.Dispose();
}
}
}
| {
"content_hash": "dad49eef404cbc75151c12acbf165b65",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 71,
"avg_line_length": 22.458333333333332,
"alnum_prop": 0.6233766233766234,
"repo_name": "mihaibulaicon/RandomTests1",
"id": "ac269e1a73d185ab9678833acf90f51a0e56d910",
"size": "541",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "RandomTests.Data/Infrastructure/DbFactory.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "98"
},
{
"name": "C#",
"bytes": "235875"
},
{
"name": "CSS",
"bytes": "76931"
},
{
"name": "HTML",
"bytes": "66523"
},
{
"name": "JavaScript",
"bytes": "283244"
},
{
"name": "SQLPL",
"bytes": "3016"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_23) on Mon Mar 25 21:50:03 CET 2013 -->
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
integrator (SLF4J 1.7.5 Test API)
</TITLE>
<META NAME="date" CONTENT="2013-03-25">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../stylesheet.css" TITLE="Style">
</HEAD>
<BODY BGCOLOR="white">
<FONT size="+1" CLASS="FrameTitleFont">
<A HREF="../integrator/package-summary.html" target="classFrame">integrator</A></FONT>
<TABLE BORDER="0" WIDTH="100%" SUMMARY="">
<TR>
<TD NOWRAP><FONT size="+1" CLASS="FrameHeadingFont">
Classes</FONT>
<FONT CLASS="FrameItemFont">
<BR>
<A HREF="Activator.html" title="class in integrator" target="classFrame">Activator</A></FONT></TD>
</TR>
</TABLE>
</BODY>
</HTML>
| {
"content_hash": "3f591e9c61e7fecea918289c6f03b9d2",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 102,
"avg_line_length": 27.303030303030305,
"alnum_prop": 0.6759156492785794,
"repo_name": "pmikee/gw2tpapp",
"id": "e23c8391c14168a3d8f0227dabb5746fe8654daa",
"size": "901",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "slf4j-1.7.5/site/testapidocs/integrator/package-frame.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "32533"
},
{
"name": "Java",
"bytes": "886509"
},
{
"name": "JavaScript",
"bytes": "39206"
}
],
"symlink_target": ""
} |
package com.avairebot.commands.administration;
import com.avairebot.AvaIre;
import com.avairebot.commands.CommandMessage;
import com.avairebot.contracts.commands.Command;
import com.avairebot.contracts.commands.CommandGroup;
import com.avairebot.contracts.commands.CommandGroups;
import com.avairebot.database.transformers.GuildTransformer;
import com.avairebot.modlog.Modlog;
import com.avairebot.modlog.ModlogAction;
import com.avairebot.modlog.ModlogType;
import com.avairebot.utilities.MentionableUtil;
import com.avairebot.utilities.RestActionUtil;
import net.dv8tion.jda.api.entities.User;
import javax.annotation.Nonnull;
import java.time.Instant;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class WarnCommand extends Command {
public WarnCommand(AvaIre avaire) {
super(avaire, false);
}
@Override
public String getName() {
return "Warn Command";
}
@Override
public String getDescription() {
return "Warns a given user with a message, this action will be reported to any channel that has modloging enabled.";
}
@Override
public List<String> getUsageInstructions() {
return Collections.singletonList(
"`:command <user> [reason]` - Warns the mentioned user with the given reason."
);
}
@Override
public List<String> getExampleUsage() {
return Collections.singletonList(
"`:command @Senither Being a potato` - Warns Senither for being a potato."
);
}
@Override
public List<Class<? extends Command>> getRelations() {
return Arrays.asList(
ModlogHistoryCommand.class,
ModlogReasonCommand.class
);
}
@Override
public List<String> getTriggers() {
return Collections.singletonList("warn");
}
@Override
public List<String> getMiddleware() {
return Arrays.asList(
"require:user,text.manage_messages",
"throttle:channel,1,5"
);
}
@Nonnull
@Override
public List<CommandGroup> getGroups() {
return Collections.singletonList(CommandGroups.MODERATION);
}
@Override
public boolean onCommand(CommandMessage context, String[] args) {
GuildTransformer transformer = context.getGuildTransformer();
if (transformer == null) {
return sendErrorMessage(context, "errors.errorOccurredWhileLoading", "server settings");
}
if (transformer.getModlog() == null) {
String prefix = generateCommandPrefix(context.getMessage());
return sendErrorMessage(context, context.i18n("requiresModlogIsEnabled", prefix));
}
User user = null;
if (args.length > 0) {
user = MentionableUtil.getUser(context, args);
}
if (user == null) {
return sendErrorMessage(context, context.i18n("mustMentionUse"));
}
if (user.isBot()) {
return sendErrorMessage(context, context.i18n("warnBots"));
}
String reason = "No reason was given.";
if (args.length > 1) {
reason = String.join(" ", Arrays.copyOfRange(args, 1, args.length));
}
ModlogAction modlogAction = new ModlogAction(
ModlogType.WARN,
context.getAuthor(), user,
reason
);
String caseId = Modlog.log(avaire, context.getGuild(), transformer, modlogAction);
if (caseId == null) {
return sendErrorMessage(context, context.i18n("failedToLogWarning"));
}
Modlog.notifyUser(user, context.getGuild(), modlogAction, caseId);
context.makeWarning(context.i18n("message"))
.set("target", user.getName() + "#" + user.getDiscriminator())
.set("reason", reason)
.setFooter("Case ID #" + caseId)
.setTimestamp(Instant.now())
.queue(ignoreMessage -> context.delete().queue(null, RestActionUtil.ignore), RestActionUtil.ignore);
return true;
}
}
| {
"content_hash": "bd4c63ca52bc039b6bc09c8e89f8b694",
"timestamp": "",
"source": "github",
"line_count": 134,
"max_line_length": 124,
"avg_line_length": 30.417910447761194,
"alnum_prop": 0.6452404317958783,
"repo_name": "AvaIre/AvaIre",
"id": "6dc08aa3608a1087a6a50a3b181e3c32a709fd03",
"size": "4778",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/avairebot/commands/administration/WarnCommand.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "597"
},
{
"name": "JavaScript",
"bytes": "613778"
},
{
"name": "Shell",
"bytes": "271"
}
],
"symlink_target": ""
} |
require "adify/version"
require "adify/helper"
require "core_ext/hash"
require "core_ext/array"
module Adify
def self.included(base)
base.send :extend, Adify
end
def adify(args)
if self.class == Class
include Adify::Methods
extend Adify::Methods
end
singleton = class << self; self; end
singleton.module_eval do
define_method(:adify_attributes=) do |hash|
@adify_attributes = hash
end
end
self.adify_attributes = args
end
module Methods
def adify_attributes
my_attributes = get_adify_attributes
merge_with = self.respond_to?(:ancestors) ? self.ancestors.slice(1,self.ancestors.length).select{|c| c.respond_to?(:adify_attributes)}.first : self.class
merge_with.respond_to?(:adify_attributes) ? merge_with.adify_attributes.adify_merge(my_attributes) : my_attributes
end
def adification(item = nil)
ad_attr = item.nil? ? self.adify_attributes : self.adify_attributes.adify_merge(item.adify_attributes)
item_for_adification = item.nil? ? self : item
ad_attr.update_values{|v| get_adify_value(item_for_adification,v)}.symbolize_keys_recursively.clone
end
private
def get_adify_attributes
(@adify_attributes || {}).clone
end
def get_adify_value(item,value)
case value.class.to_s
when "Array" then value.each.collect{|v| get_adify_value(item,v)}
when "Proc" then (value.call item).to_s
when "Hash" then value.update(value){|k,v| get_adify_value(item,v)}
when "Symbol" then item.respond_to?(value) ? item.send(value) : value
else value
end
end
end
end
ActiveRecord::Base.send :include, Adify
ActionController::Base.send :include, Adify
ActionView::Base.send :include, Adify::Helper
| {
"content_hash": "5756add16d3c298e5fa7d0dd851a7298",
"timestamp": "",
"source": "github",
"line_count": 58,
"max_line_length": 159,
"avg_line_length": 31.93103448275862,
"alnum_prop": 0.6495680345572354,
"repo_name": "smashtank/adify",
"id": "85b4b4f8251d05285c87f61d888de6504677dfa2",
"size": "1852",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/adify.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "7863"
}
],
"symlink_target": ""
} |
package com.arjuna.webservices11.wsarjtx.server;
import com.arjuna.webservices11.util.PrivilegedServiceRegistryFactory;
import com.arjuna.webservices11.wsarjtx.ArjunaTX11Constants;
import com.arjuna.webservices11.ServiceRegistry;
import org.jboss.jbossts.xts.environment.WSCEnvironmentBean;
import org.jboss.jbossts.xts.environment.WSTEnvironmentBean;
import org.jboss.jbossts.xts.environment.XTSPropertyManager;
/**
* Activate the Terminator Coordinator service
* @author kevin
*/
public class TerminationParticipantInitialisation
{
public static void startup()
{
final ServiceRegistry serviceRegistry = PrivilegedServiceRegistryFactory.getInstance().getServiceRegistry();
WSCEnvironmentBean wscEnvironmentBean = XTSPropertyManager.getWSCEnvironmentBean();
String bindAddress = wscEnvironmentBean.getBindAddress11();
int bindPort = wscEnvironmentBean.getBindPort11();
int secureBindPort = wscEnvironmentBean.getBindPortSecure11();
WSTEnvironmentBean wstEnvironmentBean = XTSPropertyManager.getWSTEnvironmentBean();
String clientServiceURLPath = wstEnvironmentBean.getClientServiceURLPath();
if (clientServiceURLPath == null) {
clientServiceURLPath = "/ws-t11-client";
}
if (bindAddress == null) {
bindAddress = "localhost";
}
if (bindPort == 0) {
bindPort = 8080;
}
if (secureBindPort == 0) {
secureBindPort = 8443;
}
final String baseUri = "http://" + bindAddress + ":" + bindPort + clientServiceURLPath;
final String uri = baseUri + "/" + ArjunaTX11Constants.TERMINATION_PARTICIPANT_SERVICE_NAME;
final String secureBaseUri = "https://" + bindAddress + ":" + secureBindPort + clientServiceURLPath;
final String secureUri = secureBaseUri + "/" + ArjunaTX11Constants.TERMINATION_PARTICIPANT_SERVICE_NAME;
serviceRegistry.registerServiceProvider(ArjunaTX11Constants.TERMINATION_PARTICIPANT_SERVICE_NAME, uri) ;
serviceRegistry.registerSecureServiceProvider(ArjunaTX11Constants.TERMINATION_PARTICIPANT_SERVICE_NAME, secureUri) ;
}
public static void shutdown()
{
}
}
| {
"content_hash": "fe5852d645e58d2985eb1582c71c7097",
"timestamp": "",
"source": "github",
"line_count": 55,
"max_line_length": 124,
"avg_line_length": 40.38181818181818,
"alnum_prop": 0.7244484466456551,
"repo_name": "nmcl/wfswarm-example-arjuna-old",
"id": "5e43faab037e6297fe2fe223f90c20c51318b70a",
"size": "3202",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "graalvm/transactions/fork/narayana/XTS/WS-T/dev/src/com/arjuna/webservices11/wsarjtx/server/TerminationParticipantInitialisation.java",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "6903"
}
],
"symlink_target": ""
} |
#import "EMTagCommand.h"
NS_ASSUME_NONNULL_BEGIN
@implementation EMTagCommand
- (NSArray<EMErrorParameter *> *)validate {
NSMutableArray<EMErrorParameter *> *ret =
[NSMutableArray<EMErrorParameter *> array];
if ([self.value length] == 0) {
[ret addObject:[self emptyStringEMErr:@"tag" field:@"tag"]];
}
return ret;
}
@end
NS_ASSUME_NONNULL_END
| {
"content_hash": "8a0434b816d58f6de0ee740571cdf41c",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 68,
"avg_line_length": 18.95,
"alnum_prop": 0.6728232189973615,
"repo_name": "scarabresearch/EmarsysPredictSDK",
"id": "da6a63c16309aa3749bbc9a195f038cf66536e83",
"size": "978",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "EmarsysPredictSDK/EMTagCommand.m",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "11149"
},
{
"name": "Objective-C",
"bytes": "134235"
},
{
"name": "Shell",
"bytes": "4871"
}
],
"symlink_target": ""
} |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using Microsoft.OData.Edm;
using Microsoft.TestCommon;
namespace System.Web.OData.Formatter
{
public class ClrTypeCacheTest
{
[Fact]
public void GetEdmType_Returns_CachedInstance()
{
ClrTypeCache cache = new ClrTypeCache();
IEdmModel model = EdmCoreModel.Instance;
IEdmTypeReference edmType1 = cache.GetEdmType(typeof(int), model);
IEdmTypeReference edmType2 = cache.GetEdmType(typeof(int), model);
Assert.NotNull(edmType1);
Assert.Same(edmType1, edmType2);
}
}
}
| {
"content_hash": "f3f1db5faadf03e94c6e6a3ece943e04",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 96,
"avg_line_length": 31,
"alnum_prop": 0.6639784946236559,
"repo_name": "lewischeng-ms/WebApi",
"id": "d60e900ed855ab9ba0b05be54dd5e56a5a5a9314",
"size": "746",
"binary": false,
"copies": "1",
"ref": "refs/heads/OData60",
"path": "OData/test/UnitTest/System.Web.OData.Test/OData/Formatter/ClrTypeCacheTest.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "1C Enterprise",
"bytes": "185749"
},
{
"name": "ASP",
"bytes": "119"
},
{
"name": "Batchfile",
"bytes": "2842"
},
{
"name": "C#",
"bytes": "14865821"
},
{
"name": "JavaScript",
"bytes": "7493"
},
{
"name": "PowerShell",
"bytes": "382"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_25) on Tue Oct 08 12:24:14 JST 2013 -->
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>twitter4j.management (twitter4j-core 3.0.4 API)</title>
<meta name="date" content="2013-10-08">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">
</head>
<body>
<h1 class="bar"><a href="../../twitter4j/management/package-summary.html" target="classFrame">twitter4j.management</a></h1>
<div class="indexContainer">
<h2 title="Interfaces">Interfaces</h2>
<ul title="Interfaces">
<li><a href="APIStatisticsMBean.html" title="interface in twitter4j.management" target="classFrame"><i>APIStatisticsMBean</i></a></li>
<li><a href="InvocationStatistics.html" title="interface in twitter4j.management" target="classFrame"><i>InvocationStatistics</i></a></li>
</ul>
<h2 title="Classes">Classes</h2>
<ul title="Classes">
<li><a href="APIStatistics.html" title="class in twitter4j.management" target="classFrame">APIStatistics</a></li>
<li><a href="APIStatisticsOpenMBean.html" title="class in twitter4j.management" target="classFrame">APIStatisticsOpenMBean</a></li>
<li><a href="InvocationStatisticsCalculator.html" title="class in twitter4j.management" target="classFrame">InvocationStatisticsCalculator</a></li>
</ul>
</div>
</body>
</html>
| {
"content_hash": "cdbacacf7566993e7c770d4c9651afac",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 147,
"avg_line_length": 54.333333333333336,
"alnum_prop": 0.7266530334014997,
"repo_name": "vaglucas/cafeUnoesc",
"id": "e9ecb6b3740b21ecec1d59d32a1485136cae8a9f",
"size": "1467",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "twitter4j-core/javadoc/twitter4j/management/package-frame.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "652842"
},
{
"name": "Java",
"bytes": "4231270"
},
{
"name": "JavaScript",
"bytes": "519974"
},
{
"name": "Shell",
"bytes": "83394"
}
],
"symlink_target": ""
} |
```
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.in28minutes</groupId>
<artifactId>in28Minutes-first-webapp</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>6.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.2</version>
<configuration>
<verbose>true</verbose>
<source>1.8</source>
<target>1.8</target>
<showWarnings>true</showWarnings>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<path>/</path>
<contextReloadable>true</contextReloadable>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
```
### \src\main\java\webapp\LoginServlet.java
```
package webapp;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(urlPatterns = "/login.do")
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
request.getRequestDispatcher("/WEB-INF/views/login.jsp").forward(request, response);
}
}
```
### \\src\main\webapp\WEB-INF\views\login.jsp
```
<html>
<head>
<title>Yahoo!!</title>
</head>
<body>
<form action="/login.do" method="POST">
Name : <input type="text" /> <input type="submit" />
</form>
</body>
</html>
```
### \src\main\webapp\WEB-INF\views\welcome.jsp
```
<html>
<head>
<title>Yahoo!!</title>
</head>
<body>
Welcome ${name}
</body>
</html>
```
### \src\main\webapp\WEB-INF\web.xml
```
<!-- webapp/WEB-INF/web.xml -->
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<display-name>To do List</display-name>
<welcome-file-list>
<welcome-file>login.do</welcome-file>
</welcome-file-list>
</web-app>
```
| {
"content_hash": "ab8b97912800dae2d32e637ef89a6e36",
"timestamp": "",
"source": "github",
"line_count": 110,
"max_line_length": 105,
"avg_line_length": 24.71818181818182,
"alnum_prop": 0.6921662375873483,
"repo_name": "in28minutes/SpringMvcStepByStep",
"id": "d9370ebe0abc78dab58ef87a2879be85974051f8",
"size": "2732",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Step05.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "12906"
}
],
"symlink_target": ""
} |
cimande
=======
BlueOxygen Cimande Workspace Project
| {
"content_hash": "d1c5d542a6f6272a8c197d23e3babe75",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 36,
"avg_line_length": 13.5,
"alnum_prop": 0.7407407407407407,
"repo_name": "blueoxygen/cimande",
"id": "2bc1dd48d88be997f211ba0fe7db0bfd35749552",
"size": "54",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "82902"
},
{
"name": "Java",
"bytes": "137365"
},
{
"name": "JavaScript",
"bytes": "62343"
}
],
"symlink_target": ""
} |
function f = abs(f, varargin)
%ABS Absolute value of a DELTAFUN object.
% ABS(F) returns the absolute value of F, where F is a DELTAFUN object such
% that the fun part of F has no roots in the domain of F. If
% ~isempty(roots(F)), then ABS(F) will return garbage with no warning.
% Copyright 2015 by The University of Oxford and The Chebfun Developers.
% See http://www.chebfun.org/ for Chebfun information.
% Take the absolute values:
f.funPart = abs(f.funPart, varargin{:});
f.deltaMag = abs(f.deltaMag);
end
| {
"content_hash": "646ca76e8d46215b85745d168a0ce303",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 77,
"avg_line_length": 37.357142857142854,
"alnum_prop": 0.7208413001912046,
"repo_name": "ilovejs/chebfun",
"id": "13e1b1d92ba298d12ee09f681d866e2521014eb9",
"size": "523",
"binary": false,
"copies": "2",
"ref": "refs/heads/development",
"path": "@deltafun/abs.m",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "M",
"bytes": "2040"
},
{
"name": "Matlab",
"bytes": "4427792"
}
],
"symlink_target": ""
} |
export default function blogServices({ models, log, elasticSearch }) {
return {
async scheduledPublish(input) {
try {
const scheduledBlogs = await models.blog.findAll();
const updates = scheduledBlogs.map(async function(scheduledBlog) {
scheduledBlog.published = true;
const updatedBlog = await scheduledBlog.save();
await elasticSearch.index(updatedBlog);
return updatedBlog;
});
await Promise.all(updates);
} catch (err) {
log.error(err);
throw err;
}
}
};
}
| {
"content_hash": "c4d19fcdff2f253b380d9806f50e72f6",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 74,
"avg_line_length": 27.666666666666668,
"alnum_prop": 0.6024096385542169,
"repo_name": "Magnetjs/magnet-core",
"id": "a000636ce5e2f3c8668a584ca2d72914d700d0d1",
"size": "581",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/v5-design/src/modules/blog/services.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "4028"
},
{
"name": "TypeScript",
"bytes": "11364"
}
],
"symlink_target": ""
} |
import { Browser } from "puppeteer-core";
import path from "upath";
import utf8 from "utf8";
import byType from "website-scraper/lib/filename-generator/by-type.js";
import { Constants } from "../Constants.js";
import { Converter } from "./Converter.js";
const { join, parse } = path;
const { encode } = utf8;
/**
* Generates filenames for the website-scraper.
*/
export class ConverterPlugin
{
/**
* The converter this plugin belongs to.
*/
private converter: Converter;
/**
* The name of the website to save.
*/
private websiteName: string;
/**
* Initializes a new instance of the {@link ConverterPlugin `ConverterPlugin`} class.
*
* @param converter
* The converter this plugin belongs to.
*
* @param websiteName
* The name of the website to save.
*/
public constructor(converter: Converter, websiteName: string)
{
this.converter = converter;
this.websiteName = websiteName;
}
/**
* Gets the converter this plugin belongs to.
*/
public get Converter(): Converter
{
return this.converter;
}
/**
* Gets the name of the website to save.
*/
public get WebsiteName(): string
{
return this.websiteName;
}
/**
* Applies the plugin.
*
* @param registerAction
* A component for registering actions.
*/
public apply(registerAction: (name: string, callback: (options: any) => any) => void): void
{
let browser: Browser;
let occupiedFilenames: string[];
let subdirectories: { [extension: string]: string };
let defaultFilename: string;
registerAction(
"beforeStart",
async ({ options }) =>
{
let browserArguments: string[] = [
...this.Converter.ChromiumArgs
];
try
{
browser = await Constants.Puppeteer.launch({
...this.Converter.BrowserOptions,
args: browserArguments
});
}
catch
{
browser = await Constants.Puppeteer.launch({
...this.Converter.BrowserOptions,
args: [
...browserArguments,
"--no-sandbox"
]
});
}
occupiedFilenames = [];
subdirectories = options.subdirectories;
defaultFilename = this.WebsiteName ?? options.defaultFilename;
});
registerAction(
"afterResponse",
async ({ response }) =>
{
if (response.request.href === this.Converter.URL)
{
return encode(await this.Converter.Document.Render());
}
else
{
let contentType = response.headers["content-type"];
let isHtml = contentType && contentType.split(";")[0] === "text/html";
if (isHtml)
{
let url = response.request.href;
let page = await browser.newPage();
await page.goto(url);
let content = await page.content();
await page.close();
return content;
}
else
{
return response.body;
}
}
});
registerAction(
"generateFilename",
({ resource }) =>
{
let result: string;
let filename: string = byType(
resource,
{
subdirectories,
defaultFilename
},
occupiedFilenames);
if (filename === "index.html")
{
result = filename = this.WebsiteName;
}
else
{
result = join(parse(defaultFilename).name, filename);
}
occupiedFilenames.push(filename);
return { filename: result };
});
}
}
| {
"content_hash": "4d884f6ec5084281a5566df1185809f2",
"timestamp": "",
"source": "github",
"line_count": 156,
"max_line_length": 95,
"avg_line_length": 28.775641025641026,
"alnum_prop": 0.45422143016261973,
"repo_name": "manuth/MarkdownConverter",
"id": "e2d9eaeffa7c83960a18fbc2039137b37cece801",
"size": "4489",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "src/Conversion/ConverterPlugin.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "26663"
},
{
"name": "HTML",
"bytes": "277"
},
{
"name": "JavaScript",
"bytes": "678"
},
{
"name": "TypeScript",
"bytes": "577705"
}
],
"symlink_target": ""
} |
var path = require('path'),
config;
var config;
if (process.env.OPENSHIFT_MYSQL_DB_HOST != undefined) {
config = {
// ### Production
// When running Ghost in the wild, use the production environment
// Configure your URL and mail settings here
production: {
url: 'https://'+process.env.OPENSHIFT_APP_DNS,
mail: {},
database: {
client: 'mysql',
connection: {
host : process.env.OPENSHIFT_MYSQL_DB_HOST,
port : process.env.OPENSHIFT_MYSQL_DB_PORT,
user : process.env.OPENSHIFT_MYSQL_DB_USERNAME,
password : process.env.OPENSHIFT_MYSQL_DB_PASSWORD,
database : process.env.OPENSHIFT_APP_NAME,
charset : 'utf8'
}
},
server: {
// Host to be passed to node's `net.Server#listen()`
host: process.env.OPENSHIFT_NODEJS_IP,
// Port to be passed to node's `net.Server#listen()`, for iisnode set this to `process.env.PORT`
port: process.env.OPENSHIFT_NODEJS_PORT
},
paths: {
contentPath: path.join(__dirname, '/content/')
}
}
}
} else if (process.env.OPENSHIFT_POSTGRESQL_DB_HOST != undefined) {
config = {
// ### Production
// When running Ghost in the wild, use the production environment
// Configure your URL and mail settings here
production: {
url: 'http://'+process.env.OPENSHIFT_APP_DNS,
mail: {},
database: {
client: 'pg',
connection: {
host : process.env.OPENSHIFT_POSTGRESQL_DB_HOST,
port : process.env.OPENSHIFT_POSTGRESQL_DB_PORT,
user : process.env.OPENSHIFT_POSTGRESQL_DB_USERNAME,
password : process.env.OPENSHIFT_POSTGRESQL_DB_PASSWORD,
database : process.env.OPENSHIFT_APP_NAME,
charset : 'utf8'
}
},
server: {
// Host to be passed to node's `net.Server#listen()`
host: process.env.OPENSHIFT_NODEJS_IP,
// Port to be passed to node's `net.Server#listen()`, for iisnode set this to `process.env.PORT`
port: process.env.OPENSHIFT_NODEJS_PORT
},
paths: {
contentPath: path.join(__dirname, '/content/')
}
}
}
} else {
config = {
// ### Development **(default)**
development: {
// The url to use when providing links to the site, E.g. in RSS and email.
url: 'http://my-ghost-blog.com',
// Example mail config
// Visit http://support.ghost.org/mail for instructions
// ```
// mail: {
// transport: 'SMTP',
// options: {
// service: 'Mailgun',
// auth: {
// user: '', // mailgun username
// pass: '' // mailgun password
// }
// }
// },
// ```
database: {
client: 'sqlite3',
connection: {
filename: path.join(__dirname, '/content/data/ghost-dev.db')
},
debug: false
},
server: {
// Host to be passed to node's `net.Server#listen()`
host: '127.0.0.1',
// Port to be passed to node's `net.Server#listen()`, for iisnode set this to `process.env.PORT`
port: '2368'
},
paths: {
contentPath: path.join(__dirname, '/content/')
}
},
// ### Production
// When running Ghost in the wild, use the production environment
// Configure your URL and mail settings here
production: {
url: 'http://'+process.env.OPENSHIFT_APP_DNS,
mail: {},
database: {
client: 'sqlite3',
connection: {
filename: path.join(__dirname, '/content/data/ghost.db')
},
debug: false
},
server: {
// Host to be passed to node's `net.Server#listen()`
host: process.env.OPENSHIFT_NODEJS_IP,
// Port to be passed to node's `net.Server#listen()`, for iisnode set this to `process.env.PORT`
port: process.env.OPENSHIFT_NODEJS_PORT
},
paths: {
contentPath: path.join(__dirname, '/content/')
}
},
// **Developers only need to edit below here**
// ### Testing
// Used when developing Ghost to run tests and check the health of Ghost
// Uses a different port number
testing: {
url: 'http://127.0.0.1:2369',
database: {
client: 'sqlite3',
connection: {
filename: path.join(__dirname, '/content/data/ghost-test.db')
}
},
server: {
host: '127.0.0.1',
port: '2369'
},
logging: false
},
// ### Testing MySQL
// Used by Travis - Automated testing run through GitHub
'testing-mysql': {
url: 'http://127.0.0.1:2369',
database: {
client: 'mysql',
connection: {
host : '127.0.0.1',
user : 'root',
password : '',
database : 'ghost_testing',
charset : 'utf8'
}
},
server: {
host: '127.0.0.1',
port: '2369'
},
logging: false
},
// ### Testing pg
// Used by Travis - Automated testing run through GitHub
'testing-pg': {
url: 'http://127.0.0.1:2369',
database: {
client: 'pg',
connection: {
host : '127.0.0.1',
user : 'postgres',
password : '',
database : 'ghost_testing',
charset : 'utf8'
}
},
server: {
host: '127.0.0.1',
port: '2369'
},
logging: false
}
};
}
// Export config
module.exports = config;
| {
"content_hash": "640069b6d8a779ba9afc2baf3e5374da",
"timestamp": "",
"source": "github",
"line_count": 193,
"max_line_length": 112,
"avg_line_length": 35.22279792746114,
"alnum_prop": 0.4339511621065019,
"repo_name": "JuceQ/openshit-ghost-zh-cn",
"id": "7a1e74af40a7002c2b28d7633c135eeb7aaf1582",
"size": "6943",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "config.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "82948"
},
{
"name": "HTML",
"bytes": "25011"
},
{
"name": "JavaScript",
"bytes": "15246"
},
{
"name": "Makefile",
"bytes": "216"
},
{
"name": "Shell",
"bytes": "851"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<!--
This is a starter template page. Use this page to start your new project from
scratch. This page gets rid of all links and provides the needed markup only.
-->
<html lang="en">
@section('htmlheader')
@include('vendor.layouts.partials.htmlheader')
@show
<!--
BODY TAG OPTIONS:
=================
Apply one or more of the following classes to get the
desired effect
|---------------------------------------------------------|
| SKINS | skin-blue |
| | skin-black |
| | skin-purple |
| | skin-yellow |
| | skin-red |
| | skin-green |
|---------------------------------------------------------|
|LAYOUT OPTIONS | fixed |
| | layout-boxed |
| | layout-top-nav |
| | sidebar-collapse |
| | sidebar-mini |
|---------------------------------------------------------|
-->
<body class="skin-blue layout-top-nav control-sidebar-open">
<div id="app">
<div class="wrapper">
@include('vendor.layouts.partials.mainheader-map')
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
@include('vendor.layouts.partials.contentheader')
<!-- Main content -->
<section class="content">
<!-- Your Page Content Here -->
@yield('main-content')
</section><!-- /.content -->
</div><!-- /.content-wrapper -->
@include('vendor.layouts.partials.controlsidebar')
@include('vendor.layouts.partials.footer')
</div><!-- ./wrapper -->
</div>
@section('scripts')
@include('vendor.layouts.partials.scripts')
@show
</body>
</html>
| {
"content_hash": "f41f56431e6bbf04173ecd308d23474b",
"timestamp": "",
"source": "github",
"line_count": 62,
"max_line_length": 77,
"avg_line_length": 32.016129032258064,
"alnum_prop": 0.4292191435768262,
"repo_name": "robkedzior/telegram-panel",
"id": "faefb7454807cf46c0de550cd54485632d22a934",
"size": "1985",
"binary": false,
"copies": "1",
"ref": "refs/heads/Telegram",
"path": "src/Laravel/resources/views/layouts/app-map.blade.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "1404813"
},
{
"name": "HTML",
"bytes": "2155405"
},
{
"name": "JavaScript",
"bytes": "2850297"
},
{
"name": "PHP",
"bytes": "422314"
},
{
"name": "Shell",
"bytes": "1040"
},
{
"name": "Vue",
"bytes": "1122"
}
],
"symlink_target": ""
} |
// Author: pulkitg@google.com (Pulkit Goyal)
#include "net/instaweb/rewriter/public/critical_images_finder.h"
#include "net/instaweb/http/public/logging_proto_impl.h"
#include "net/instaweb/rewriter/critical_images.pb.h"
#include "net/instaweb/rewriter/critical_keys.pb.h"
#include "net/instaweb/rewriter/public/critical_images_finder_test_base.h"
#include "net/instaweb/rewriter/public/property_cache_util.h"
#include "net/instaweb/rewriter/public/rewrite_driver.h"
#include "net/instaweb/rewriter/public/rewrite_options.h"
#include "net/instaweb/rewriter/rendered_image.pb.h"
#include "net/instaweb/util/public/google_url.h"
#include "net/instaweb/util/public/gtest.h"
#include "net/instaweb/util/public/property_cache.h"
#include "net/instaweb/util/public/proto_util.h"
#include "net/instaweb/util/public/scoped_ptr.h"
#include "pagespeed/kernel/base/timer.h"
namespace net_instaweb {
namespace {
// Mock class for testing a critical image finder like the beacon finder that
// stores a history of previous critical image sets.
class HistoryTestCriticalImagesFinder : public TestCriticalImagesFinder {
public:
HistoryTestCriticalImagesFinder(const PropertyCache::Cohort* cohort,
Statistics* stats)
: TestCriticalImagesFinder(cohort, stats) {}
virtual int PercentSeenForCritical() const {
return 80;
}
virtual int SupportInterval() const {
return 10;
}
};
const char kCriticalImagesCohort[] = "critical_images";
} // namespace
class CriticalImagesFinderTest : public CriticalImagesFinderTestBase {
public:
virtual CriticalImagesFinder* finder() { return finder_.get(); }
protected:
virtual void SetUp() {
CriticalImagesFinderTestBase::SetUp();
SetupCohort(page_property_cache(), kCriticalImagesCohort);
finder_.reset(new TestCriticalImagesFinder(
page_property_cache()->GetCohort(kCriticalImagesCohort), statistics()));
ResetDriver();
}
private:
friend class CriticalImagesHistoryFinderTest;
scoped_ptr<TestCriticalImagesFinder> finder_;
};
class CriticalImagesHistoryFinderTest : public CriticalImagesFinderTest {
protected:
virtual void SetUp() {
CriticalImagesFinderTestBase::SetUp();
SetupCohort(page_property_cache(), kCriticalImagesCohort);
finder_.reset(new HistoryTestCriticalImagesFinder(
page_property_cache()->GetCohort(kCriticalImagesCohort), statistics()));
ResetDriver();
}
};
TEST_F(CriticalImagesFinderTest, UpdateCriticalImagesCacheEntrySuccess) {
// Include an actual value in the RPC result to induce a cache write.
StringSet html_critical_images_set;
html_critical_images_set.insert("imageA.jpeg");
StringSet css_critical_images_set;
css_critical_images_set.insert("imageB.jpeg");
EXPECT_TRUE(UpdateCriticalImagesCacheEntry(
&html_critical_images_set, &css_critical_images_set));
EXPECT_TRUE(GetCriticalImagesUpdatedValue()->has_value());
// Verify the contents of the support protobuf, and ensure we're no longer
// generating legacy data.
ArrayInputStream input(GetCriticalImagesUpdatedValue()->value().data(),
GetCriticalImagesUpdatedValue()->value().size());
CriticalImages parsed_proto;
parsed_proto.ParseFromZeroCopyStream(&input);
ASSERT_TRUE(parsed_proto.has_html_critical_image_support());
const CriticalKeys& html_support = parsed_proto.html_critical_image_support();
EXPECT_EQ(1, html_support.key_evidence_size());
ASSERT_TRUE(parsed_proto.has_css_critical_image_support());
const CriticalKeys& css_support = parsed_proto.css_critical_image_support();
EXPECT_EQ(1, css_support.key_evidence_size());
}
TEST_F(CriticalImagesFinderTest,
UpdateCriticalImagesCacheEntrySuccessEmptySet) {
// Include an actual value in the RPC result to induce a cache write.
StringSet html_critical_images_set;
StringSet css_critical_images_set;
EXPECT_TRUE(UpdateCriticalImagesCacheEntry(
&html_critical_images_set, &css_critical_images_set));
EXPECT_TRUE(GetCriticalImagesUpdatedValue()->has_value());
EXPECT_TRUE(GetCriticalImagesUpdatedValue()->has_value());
rewrite_driver()->property_page()->WriteCohort(finder()->cohort());
}
TEST_F(CriticalImagesFinderTest, UpdateCriticalImagesCacheEntrySetNULL) {
EXPECT_FALSE(UpdateCriticalImagesCacheEntry(NULL, NULL));
EXPECT_FALSE(GetCriticalImagesUpdatedValue()->has_value());
}
TEST_F(CriticalImagesFinderTest,
UpdateCriticalImagesCacheEntryPropertyPageMissing) {
// No cache insert if PropertyPage is not set in RewriteDriver.
rewrite_driver()->set_property_page(NULL);
// Include an actual value in the RPC result to induce a cache write. We
// expect no writes, but not from a lack of results!
StringSet html_critical_images_set;
StringSet css_critical_images_set;
EXPECT_FALSE(UpdateCriticalImagesCacheEntry(
&html_critical_images_set, &css_critical_images_set));
EXPECT_EQ(NULL, GetCriticalImagesUpdatedValue());
}
TEST_F(CriticalImagesFinderTest, GetCriticalImagesTest) {
// First it will insert the value in cache, then it retrieves critical images.
// Include an actual value in the RPC result to induce a cache write.
StringSet html_critical_images_set;
html_critical_images_set.insert("imageA.jpeg");
html_critical_images_set.insert("imageB.jpeg");
StringSet css_critical_images_set;
css_critical_images_set.insert("imageD.jpeg");
// Calling IsHtmlCriticalImage should update the CriticalImagesInfo in
// RewriteDriver.
EXPECT_FALSE(IsHtmlCriticalImage("imageA.jpg"));
// We should get 1 miss for the critical images value.
CheckCriticalImageFinderStats(0, 0, 1);
// Here and below, -1 results mean "no critical image data reported".
EXPECT_EQ(-1, logging_info()->num_html_critical_images());
EXPECT_EQ(-1, logging_info()->num_css_critical_images());
ClearStats();
// Calling IsHtmlCriticalImage again should not update the stats, because the
// CriticalImagesInfo has already been updated.
EXPECT_FALSE(IsHtmlCriticalImage("imageA.jpg"));
CheckCriticalImageFinderStats(0, 0, 0);
// ClearStats() creates a new request context and hence a new log record. So
// the critical image counts are not set.
EXPECT_EQ(-1, logging_info()->num_html_critical_images());
EXPECT_EQ(-1, logging_info()->num_css_critical_images());
ClearStats();
EXPECT_TRUE(UpdateCriticalImagesCacheEntry(
&html_critical_images_set, &css_critical_images_set));
// Write the updated value to the pcache.
rewrite_driver()->property_page()->WriteCohort(finder()->cohort());
EXPECT_TRUE(GetCriticalImagesUpdatedValue()->has_value());
// critical_images_info() is NULL because there is no previous call to
// GetCriticalImages()
ResetDriver();
EXPECT_TRUE(rewrite_driver()->critical_images_info() == NULL);
EXPECT_TRUE(IsHtmlCriticalImage("imageA.jpeg"));
CheckCriticalImageFinderStats(1, 0, 0);
EXPECT_EQ(2, logging_info()->num_html_critical_images());
EXPECT_EQ(1, logging_info()->num_css_critical_images());
ClearStats();
// GetCriticalImages() updates critical_images set in RewriteDriver().
EXPECT_TRUE(rewrite_driver()->critical_images_info() != NULL);
// EXPECT_EQ(2, GetCriticalImages(rewrite_driver()).size());
EXPECT_TRUE(IsHtmlCriticalImage("imageA.jpeg"));
EXPECT_TRUE(IsHtmlCriticalImage("imageB.jpeg"));
EXPECT_FALSE(IsHtmlCriticalImage("imageC.jpeg"));
// EXPECT_EQ(1, css_critical_images->size());
EXPECT_TRUE(IsCssCriticalImage("imageD.jpeg"));
EXPECT_FALSE(IsCssCriticalImage("imageA.jpeg"));
// Reset the driver, read the page and call UpdateCriticalImagesSetInDriver by
// calling IsHtmlCriticalImage.
// We read it from cache.
ResetDriver();
EXPECT_TRUE(IsHtmlCriticalImage("imageA.jpeg"));
CheckCriticalImageFinderStats(1, 0, 0);
EXPECT_EQ(2, logging_info()->num_html_critical_images());
EXPECT_EQ(1, logging_info()->num_css_critical_images());
ClearStats();
// Advance to 90% of expiry. We get a hit from cache and must_compute is true.
AdvanceTimeMs(0.9 * options()->finder_properties_cache_expiration_time_ms());
ResetDriver();
EXPECT_TRUE(IsHtmlCriticalImage("imageA.jpeg"));
CheckCriticalImageFinderStats(1, 0, 0);
EXPECT_EQ(2, logging_info()->num_html_critical_images());
EXPECT_EQ(1, logging_info()->num_css_critical_images());
ClearStats();
ResetDriver();
// Advance past expiry, so that the pages expire; now no images are critical.
AdvanceTimeMs(2 * options()->finder_properties_cache_expiration_time_ms());
EXPECT_TRUE(rewrite_driver()->critical_images_info() == NULL);
EXPECT_FALSE(IsHtmlCriticalImage("imageA.jpeg"));
EXPECT_TRUE(rewrite_driver()->critical_images_info() != NULL);
CheckCriticalImageFinderStats(0, 1, 0);
// Here -1 results mean "no valid critical image data" due to expiry.
EXPECT_EQ(-1, logging_info()->num_html_critical_images());
EXPECT_EQ(-1, logging_info()->num_css_critical_images());
}
TEST_F(CriticalImagesHistoryFinderTest, GetCriticalImagesTest) {
// Verify that storing multiple critical images, like we do with the beacon
// critical image finder, works correctly.
// Write images to property cache, ensuring that they are critical images
StringSet html_critical_images_set;
html_critical_images_set.insert("imgA.jpeg");
html_critical_images_set.insert("imgB.jpeg");
StringSet css_critical_images_set;
css_critical_images_set.insert("imgD.jpeg");
for (int i = 0; i < finder()->SupportInterval() * 3; ++i) {
ResetDriver();
EXPECT_TRUE(UpdateCriticalImagesCacheEntry(
&html_critical_images_set, &css_critical_images_set));
rewrite_driver()->property_page()->WriteCohort(finder()->cohort());
ResetDriver();
EXPECT_TRUE(IsHtmlCriticalImage("imgA.jpeg"));
EXPECT_TRUE(IsHtmlCriticalImage("imgB.jpeg"));
EXPECT_TRUE(IsCssCriticalImage("imgD.jpeg"));
EXPECT_FALSE(IsCssCriticalImage("imgA.jpeg"));
}
// Now, write just imgA twice. Since our limit is set to 80%, B should still
// be critical afterwards.
html_critical_images_set.clear();
html_critical_images_set.insert("imgA.jpeg");
for (int i = 0; i < 2; ++i) {
ResetDriver();
EXPECT_TRUE(UpdateCriticalImagesCacheEntry(
&html_critical_images_set, NULL));
rewrite_driver()->property_page()->WriteCohort(finder()->cohort());
ResetDriver();
EXPECT_TRUE(IsHtmlCriticalImage("imgA.jpeg"));
EXPECT_TRUE(IsHtmlCriticalImage("imgB.jpeg"));
EXPECT_TRUE(IsCssCriticalImage("imgD.jpeg"));
}
// Continue writing imgA, but now imgB should be below our threshold.
for (int i = 0; i < finder()->SupportInterval(); ++i) {
ResetDriver();
EXPECT_TRUE(UpdateCriticalImagesCacheEntry(
&html_critical_images_set, NULL));
rewrite_driver()->property_page()->WriteCohort(finder()->cohort());
ResetDriver();
EXPECT_TRUE(IsHtmlCriticalImage("imgA.jpeg"));
EXPECT_FALSE(IsHtmlCriticalImage("imgB.jpeg"));
// We didn't write CSS critical images, so imgD should still be critical.
EXPECT_TRUE(IsCssCriticalImage("imgD.jpeg"));
}
// Write imgC twice. imgA should still be critical, and C should not.
html_critical_images_set.clear();
html_critical_images_set.insert("imgC.jpeg");
for (int i = 0; i < 2; ++i) {
ResetDriver();
EXPECT_TRUE(UpdateCriticalImagesCacheEntry(
&html_critical_images_set, NULL));
rewrite_driver()->property_page()->WriteCohort(finder()->cohort());
ResetDriver();
EXPECT_TRUE(IsHtmlCriticalImage("imgA.jpeg"));
EXPECT_FALSE(IsHtmlCriticalImage("imgB.jpeg"));
EXPECT_FALSE(IsHtmlCriticalImage("imgC.jpeg"));
EXPECT_TRUE(IsCssCriticalImage("imgD.jpeg"));
}
// Continue writing imgC; it won't have enough support to make it critical,
// and A should no longer be critical. That's because the maximum possible
// support value will have saturated, so we need a fair amount of support
// before we reach the saturated value. Basically we're iterating until:
// sum{k<-1..n} ((s(s-1))/s)^k >= r sum{k<-1..infinity} ((s(s-1)/s)^k
// And in this case, where s=10 and r=80%, k happens to be 14 (2 iterations
// above and 12 iterations here). To make things more fun, the above
// calculations are done approximately using integer arithmetic, which makes
// the limit much easier to compute.
for (int i = 0; i < 12; ++i) {
ResetDriver();
EXPECT_TRUE(UpdateCriticalImagesCacheEntry(
&html_critical_images_set, NULL));
rewrite_driver()->property_page()->WriteCohort(finder()->cohort());
ResetDriver();
EXPECT_FALSE(IsHtmlCriticalImage("imgA.jpeg"));
EXPECT_FALSE(IsHtmlCriticalImage("imgB.jpeg"));
EXPECT_FALSE(IsHtmlCriticalImage("imgC.jpeg"));
EXPECT_TRUE(IsCssCriticalImage("imgD.jpeg"));
}
// And finally, write imgC, making sure it is critical.
for (int i = 0; i < finder()->SupportInterval(); ++i) {
ResetDriver();
EXPECT_TRUE(UpdateCriticalImagesCacheEntry(
&html_critical_images_set, NULL));
rewrite_driver()->property_page()->WriteCohort(finder()->cohort());
ResetDriver();
EXPECT_FALSE(IsHtmlCriticalImage("imgA.jpeg"));
EXPECT_FALSE(IsHtmlCriticalImage("imgB.jpeg"));
EXPECT_TRUE(IsHtmlCriticalImage("imgC.jpeg"));
EXPECT_TRUE(IsCssCriticalImage("imgD.jpeg"));
}
}
TEST_F(CriticalImagesFinderTest, NoCriticalImages) {
// Make sure we deal gracefully when there are no critical images in a beacon
// result.
StringSet critical;
EXPECT_TRUE(critical.empty());
EXPECT_TRUE(UpdateCriticalImagesCacheEntry(&critical, &critical));
rewrite_driver()->property_page()->WriteCohort(finder()->cohort());
ResetDriver();
EXPECT_FALSE(IsHtmlCriticalImage("imgA.jpeg"));
EXPECT_FALSE(IsCssCriticalImage("imgA.jpeg"));
EXPECT_TRUE(finder()->GetHtmlCriticalImages(rewrite_driver()).empty());
EXPECT_TRUE(finder()->GetCssCriticalImages(rewrite_driver()).empty());
// Now register critical images and make sure we can leave the empty state.
critical.insert("imgA.jpeg");
for (int i = 0; i < finder()->SupportInterval(); ++i) {
EXPECT_TRUE(UpdateCriticalImagesCacheEntry(&critical, &critical));
}
rewrite_driver()->property_page()->WriteCohort(finder()->cohort());
ResetDriver();
EXPECT_TRUE(IsHtmlCriticalImage("imgA.jpeg"));
EXPECT_TRUE(IsCssCriticalImage("imgA.jpeg"));
}
TEST_F(CriticalImagesFinderTest, TestRenderedImageExtractionFromPropertyCache) {
RenderedImages rendered_images;
RenderedImages_Image* images = rendered_images.add_image();
GoogleString url_str = "http://example.com/imageA.jpeg";
images->set_src(url_str);
images->set_rendered_width(40);
images->set_rendered_height(54);
PropertyPage* page = rewrite_driver()->property_page();
UpdateInPropertyCache(rendered_images, finder()->cohort(),
finder()->kRenderedImageDimensionsProperty,
false /* don't write cohort */, page);
// Check if Finder extracts properly.
scoped_ptr<RenderedImages> extracted_rendered_images(
finder()->ExtractRenderedImageDimensionsFromCache(rewrite_driver()));
EXPECT_EQ(1, extracted_rendered_images->image_size());
EXPECT_STREQ(url_str, extracted_rendered_images->image(0).src());
EXPECT_EQ(40, extracted_rendered_images->image(0).rendered_width());
EXPECT_EQ(54, extracted_rendered_images->image(0).rendered_height());
options()->EnableFilter(RewriteOptions::kResizeToRenderedImageDimensions);
std::pair<int32, int32> dimensions;
GoogleUrl gurl(url_str);
EXPECT_TRUE(finder()->GetRenderedImageDimensions(rewrite_driver(), gurl,
&dimensions));
EXPECT_EQ(std::make_pair(40, 54), dimensions);
}
} // namespace net_instaweb
| {
"content_hash": "2a888bf03e9d49ce9fce8dedb311af3d",
"timestamp": "",
"source": "github",
"line_count": 368,
"max_line_length": 80,
"avg_line_length": 42.63586956521739,
"alnum_prop": 0.7226258763543658,
"repo_name": "webhost/mod_pagespeed",
"id": "ff609df6c890b9041cf3b97a2429055755ae24f2",
"size": "16285",
"binary": false,
"copies": "1",
"ref": "refs/heads/latest-stable",
"path": "net/instaweb/rewriter/critical_images_finder_test.cc",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "1639"
},
{
"name": "C",
"bytes": "30586"
},
{
"name": "C++",
"bytes": "12033228"
},
{
"name": "CSS",
"bytes": "65947"
},
{
"name": "HTML",
"bytes": "203277"
},
{
"name": "JavaScript",
"bytes": "2365110"
},
{
"name": "Makefile",
"bytes": "33813"
},
{
"name": "Objective-C++",
"bytes": "1308"
},
{
"name": "PHP",
"bytes": "661"
},
{
"name": "Perl",
"bytes": "14872"
},
{
"name": "Protocol Buffer",
"bytes": "57074"
},
{
"name": "Python",
"bytes": "190375"
},
{
"name": "Shell",
"bytes": "314042"
}
],
"symlink_target": ""
} |
import * as React from 'react';
declare namespace F7SkeletonText {
interface Props {
slot? : string
id? : string | number
className? : string
style? : React.CSSProperties
width? : number | string
height? : number | string
tag? : string
color? : string
colorTheme? : string
textColor? : string
bgColor? : string
borderColor? : string
rippleColor? : string
themeDark? : boolean
}
}
declare class F7SkeletonText extends React.Component<F7SkeletonText.Props, {}> {
}
export default F7SkeletonText; | {
"content_hash": "bc482a1509bfcf4d104d0620eb762bf2",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 80,
"avg_line_length": 22.48,
"alnum_prop": 0.6583629893238434,
"repo_name": "iamxiaoma/Framework7",
"id": "117601d17a61c92ec298c3c0a430e70d8b8e0517",
"size": "562",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "packages/react/components/skeleton-text.d.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2793272"
},
{
"name": "HTML",
"bytes": "1736456"
},
{
"name": "JavaScript",
"bytes": "8961486"
},
{
"name": "Python",
"bytes": "5864"
},
{
"name": "Shell",
"bytes": "4780"
},
{
"name": "Vue",
"bytes": "539760"
}
],
"symlink_target": ""
} |
package org.lambda4j.function.tri.obj;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class BiObjByteToIntFunctionTest {
@Test
void of_givenExpression_returnsFunctionalInterface() {
BiObjByteToIntFunction<String, String> function =
BiObjByteToIntFunction.of((t, u, value) -> Integer.parseInt(t));
Assertions.assertNotNull(function);
}
@Test
void of_givenNull_returnsNull() {
BiObjByteToIntFunction<String, String> function = BiObjByteToIntFunction.of(null);
Assertions.assertNull(function);
}
}
| {
"content_hash": "f0bb939c59c2fb2fb6ca3dd9f2b239c6",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 90,
"avg_line_length": 27.363636363636363,
"alnum_prop": 0.7043189368770764,
"repo_name": "Gridtec/lambda4j",
"id": "a2daac16f1ef37d00f78d5948e440e1bcebaf939",
"size": "1210",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lambda4j/src/test/java/org/lambda4j/function/tri/obj/BiObjByteToIntFunctionTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "7381033"
}
],
"symlink_target": ""
} |
import os
from setuptools import setup, find_packages
from contact_form import get_version as get_package_version
README = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read()
REQUIREMENTS = os.path.join(os.path.dirname(__file__), 'requirements.txt')
reqs = open(REQUIREMENTS).read().splitlines()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-cbv-contact-form',
version=get_package_version(),
packages=find_packages(),
include_package_data=True,
install_requires=reqs,
license='BSD',
description='Class based view contact form with captcha support for Django 1.5+',
long_description=README,
url='https://github.com/dlancer/django-cbv-contact-form',
author='dlancer',
author_email='dmdpost@gmail.com',
maintainer='dlancer',
maintainer_email='dmdpost@gmail.com',
zip_safe=False,
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Development Status :: 2 - Pre-Alpha',
],
)
| {
"content_hash": "1f4f369394f78c0c532c7d0c03dd44ab",
"timestamp": "",
"source": "github",
"line_count": 42,
"max_line_length": 85,
"avg_line_length": 37.357142857142854,
"alnum_prop": 0.6481835564053537,
"repo_name": "joebos/django-cbv-contact-form",
"id": "67064018e7a2da6fc0ea94bd30bb6e8e2932bcc9",
"size": "1569",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "setup.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "HTML",
"bytes": "437"
},
{
"name": "Python",
"bytes": "31612"
}
],
"symlink_target": ""
} |
@interface DynamicContentFirstViewController : UIViewController <MZFormSheetPresentationContentSizing>
@end
| {
"content_hash": "edd6de23c5bfbfa83fde2b56478e0788",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 102,
"avg_line_length": 36.333333333333336,
"alnum_prop": 0.8899082568807339,
"repo_name": "OmarPedraza/MZFormSheetPresentationController",
"id": "85e8d0d172fced9f738c67075128027777f039fa",
"size": "401",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Example/Objective-C/MZFormSheetPresentationController Objective-C Example/DynamicContentFirstViewController.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "653"
},
{
"name": "Objective-C",
"bytes": "247927"
},
{
"name": "Ruby",
"bytes": "937"
},
{
"name": "Shell",
"bytes": "22796"
},
{
"name": "Swift",
"bytes": "19440"
}
],
"symlink_target": ""
} |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
** Header: AppDomain.cpp
**
**
** Purpose: Implements AppDomain (loader domain) architecture
**
**
===========================================================*/
#ifndef _APPDOMAIN_H
#define _APPDOMAIN_H
#include "eventtrace.h"
#include "assembly.hpp"
#include "clsload.hpp"
#include "eehash.h"
#ifdef FEATURE_FUSION
#include "fusion.h"
#endif
#include "arraylist.h"
#include "comreflectioncache.hpp"
#include "comutilnative.h"
#include "domainfile.h"
#include "objectlist.h"
#include "fptrstubs.h"
#include "ilstubcache.h"
#include "testhookmgr.h"
#ifdef FEATURE_VERSIONING
#include "../binder/inc/applicationcontext.hpp"
#endif // FEATURE_VERSIONING
#include "rejit.h"
#ifdef FEATURE_MULTICOREJIT
#include "multicorejit.h"
#endif
#ifdef FEATURE_COMINTEROP
#include "clrprivbinderwinrt.h"
#ifndef FEATURE_CORECLR
#include "clrprivbinderreflectiononlywinrt.h"
#include "clrprivtypecachereflectiononlywinrt.h"
#endif
#include "..\md\winmd\inc\adapter.h"
#include "winrttypenameconverter.h"
#endif // FEATURE_COMINTEROP
#include "appxutil.h"
class BaseDomain;
class SystemDomain;
class SharedDomain;
class AppDomain;
class CompilationDomain;
class AppDomainEnum;
class AssemblySink;
class EEMarshalingData;
class Context;
class GlobalStringLiteralMap;
class StringLiteralMap;
struct SecurityContext;
class MngStdInterfacesInfo;
class DomainModule;
class DomainAssembly;
struct InteropMethodTableData;
class LoadLevelLimiter;
class UMEntryThunkCache;
class TypeEquivalenceHashTable;
class IApplicationSecurityDescriptor;
class StringArrayList;
typedef VPTR(IApplicationSecurityDescriptor) PTR_IApplicationSecurityDescriptor;
extern INT64 g_PauseTime; // Total time in millisecond the CLR has been paused
#ifdef FEATURE_COMINTEROP
class ComCallWrapperCache;
struct SimpleComCallWrapper;
class RCWRefCache;
// This enum is used to specify whether user want COM or remoting
enum COMorRemotingFlag {
COMorRemoting_NotInitialized = 0,
COMorRemoting_COM = 1, // COM will be used both cross-domain and cross-runtime
COMorRemoting_Remoting = 2, // Remoting will be used cross-domain; cross-runtime will use Remoting only if it looks like it's expected (default)
COMorRemoting_LegacyMode = 3 // Remoting will be used both cross-domain and cross-runtime
};
#endif // FEATURE_COMINTEROP
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4200) // Disable zero-sized array warning
#endif
GPTR_DECL(IdDispenser, g_pModuleIndexDispenser);
// This enum is aligned to System.ExceptionCatcherType.
enum ExceptionCatcher {
ExceptionCatcher_ManagedCode = 0,
ExceptionCatcher_AppDomainTransition = 1,
ExceptionCatcher_COMInterop = 2,
};
// We would like *ALLOCATECLASS_FLAG to AV (in order to catch errors), so don't change it
struct ClassInitFlags {
enum
{
INITIALIZED_FLAG_BIT = 0,
INITIALIZED_FLAG = 1<<INITIALIZED_FLAG_BIT,
ERROR_FLAG_BIT = 1,
ERROR_FLAG = 1<<ERROR_FLAG_BIT,
ALLOCATECLASS_FLAG_BIT = 2, // Bit to avoid racing for InstantiateStaticHandles
ALLOCATECLASS_FLAG = 1<<ALLOCATECLASS_FLAG_BIT,
COLLECTIBLE_FLAG_BIT = 3,
COLLECTIBLE_FLAG = 1<<COLLECTIBLE_FLAG_BIT
};
};
struct DomainLocalModule
{
friend class ClrDataAccess;
friend class CheckAsmOffsets;
friend struct ThreadLocalModule;
// After these macros complete, they may have returned an interior pointer into a gc object. This pointer will have been cast to a byte pointer
// It is critically important that no GC is allowed to occur before this pointer is used.
#define GET_DYNAMICENTRY_GCSTATICS_BASEPOINTER(pLoaderAllocator, dynamicClassInfoParam, pGCStatics) \
{\
DomainLocalModule::PTR_DynamicClassInfo dynamicClassInfo = dac_cast<DomainLocalModule::PTR_DynamicClassInfo>(dynamicClassInfoParam);\
DomainLocalModule::PTR_DynamicEntry pDynamicEntry = dac_cast<DomainLocalModule::PTR_DynamicEntry>((DomainLocalModule::DynamicEntry*)dynamicClassInfo->m_pDynamicEntry.Load()); \
if ((dynamicClassInfo->m_dwFlags) & ClassInitFlags::COLLECTIBLE_FLAG) \
{\
PTRARRAYREF objArray;\
objArray = (PTRARRAYREF)pLoaderAllocator->GetHandleValueFastCannotFailType2( \
(dac_cast<DomainLocalModule::PTR_CollectibleDynamicEntry>(pDynamicEntry))->m_hGCStatics);\
*(pGCStatics) = dac_cast<PTR_BYTE>(PTR_READ(PTR_TO_TADDR(OBJECTREFToObject( objArray )) + offsetof(PtrArray, m_Array), objArray->GetNumComponents() * sizeof(void*))) ;\
}\
else\
{\
*(pGCStatics) = (dac_cast<DomainLocalModule::PTR_NormalDynamicEntry>(pDynamicEntry))->GetGCStaticsBasePointer();\
}\
}\
#define GET_DYNAMICENTRY_NONGCSTATICS_BASEPOINTER(pLoaderAllocator, dynamicClassInfoParam, pNonGCStatics) \
{\
DomainLocalModule::PTR_DynamicClassInfo dynamicClassInfo = dac_cast<DomainLocalModule::PTR_DynamicClassInfo>(dynamicClassInfoParam);\
DomainLocalModule::PTR_DynamicEntry pDynamicEntry = dac_cast<DomainLocalModule::PTR_DynamicEntry>((DomainLocalModule::DynamicEntry*)(dynamicClassInfo)->m_pDynamicEntry.Load()); \
if (((dynamicClassInfo)->m_dwFlags) & ClassInitFlags::COLLECTIBLE_FLAG) \
{\
if ((dac_cast<DomainLocalModule::PTR_CollectibleDynamicEntry>(pDynamicEntry))->m_hNonGCStatics != 0) \
{ \
U1ARRAYREF objArray;\
objArray = (U1ARRAYREF)pLoaderAllocator->GetHandleValueFastCannotFailType2( \
(dac_cast<DomainLocalModule::PTR_CollectibleDynamicEntry>(pDynamicEntry))->m_hNonGCStatics);\
*(pNonGCStatics) = dac_cast<PTR_BYTE>(PTR_READ( \
PTR_TO_TADDR(OBJECTREFToObject( objArray )) + sizeof(ArrayBase) - DomainLocalModule::DynamicEntry::GetOffsetOfDataBlob(), \
objArray->GetNumComponents() * (DWORD)objArray->GetComponentSize() + DomainLocalModule::DynamicEntry::GetOffsetOfDataBlob())); \
} else (*pNonGCStatics) = NULL; \
}\
else\
{\
*(pNonGCStatics) = dac_cast<DomainLocalModule::PTR_NormalDynamicEntry>(pDynamicEntry)->GetNonGCStaticsBasePointer();\
}\
}\
struct DynamicEntry
{
static DWORD GetOffsetOfDataBlob();
};
typedef DPTR(DynamicEntry) PTR_DynamicEntry;
struct CollectibleDynamicEntry : public DynamicEntry
{
LOADERHANDLE m_hGCStatics;
LOADERHANDLE m_hNonGCStatics;
};
typedef DPTR(CollectibleDynamicEntry) PTR_CollectibleDynamicEntry;
struct NormalDynamicEntry : public DynamicEntry
{
PTR_OBJECTREF m_pGCStatics;
#ifdef FEATURE_64BIT_ALIGNMENT
// Padding to make m_pDataBlob aligned at MAX_PRIMITIVE_FIELD_SIZE
// code:MethodTableBuilder::PlaceRegularStaticFields assumes that the start of the data blob is aligned
SIZE_T m_padding;
#endif
BYTE m_pDataBlob[0];
inline PTR_BYTE GetGCStaticsBasePointer()
{
LIMITED_METHOD_CONTRACT;
SUPPORTS_DAC;
return dac_cast<PTR_BYTE>(m_pGCStatics);
}
inline PTR_BYTE GetNonGCStaticsBasePointer()
{
LIMITED_METHOD_CONTRACT
SUPPORTS_DAC;
return dac_cast<PTR_BYTE>(this);
}
};
typedef DPTR(NormalDynamicEntry) PTR_NormalDynamicEntry;
struct DynamicClassInfo
{
VolatilePtr<DynamicEntry, PTR_DynamicEntry> m_pDynamicEntry;
Volatile<DWORD> m_dwFlags;
};
typedef DPTR(DynamicClassInfo) PTR_DynamicClassInfo;
inline UMEntryThunk * GetADThunkTable()
{
LIMITED_METHOD_CONTRACT
return m_pADThunkTable;
}
inline void SetADThunkTable(UMEntryThunk* pADThunkTable)
{
LIMITED_METHOD_CONTRACT
InterlockedCompareExchangeT(m_pADThunkTable.GetPointer(), pADThunkTable, NULL);
}
// Note the difference between:
//
// GetPrecomputedNonGCStaticsBasePointer() and
// GetPrecomputedStaticsClassData()
//
// GetPrecomputedNonGCStaticsBasePointer returns the pointer that should be added to field offsets to retrieve statics
// GetPrecomputedStaticsClassData returns a pointer to the first byte of the precomputed statics block
inline TADDR GetPrecomputedNonGCStaticsBasePointer()
{
LIMITED_METHOD_CONTRACT
return dac_cast<TADDR>(this);
}
inline PTR_BYTE GetPrecomputedStaticsClassData()
{
LIMITED_METHOD_CONTRACT
return dac_cast<PTR_BYTE>(this) + offsetof(DomainLocalModule, m_pDataBlob);
}
static SIZE_T GetOffsetOfDataBlob() { return offsetof(DomainLocalModule, m_pDataBlob); }
static SIZE_T GetOffsetOfGCStaticPointer() { return offsetof(DomainLocalModule, m_pGCStatics); }
inline DomainFile* GetDomainFile()
{
LIMITED_METHOD_CONTRACT
SUPPORTS_DAC;
return m_pDomainFile;
}
#ifndef DACCESS_COMPILE
inline void SetDomainFile(DomainFile* pDomainFile)
{
LIMITED_METHOD_CONTRACT
m_pDomainFile = pDomainFile;
}
#endif
inline PTR_OBJECTREF GetPrecomputedGCStaticsBasePointer()
{
LIMITED_METHOD_CONTRACT
return m_pGCStatics;
}
inline PTR_OBJECTREF * GetPrecomputedGCStaticsBasePointerAddress()
{
LIMITED_METHOD_CONTRACT
return &m_pGCStatics;
}
// Returns bytes so we can add offsets
inline PTR_BYTE GetGCStaticsBasePointer(MethodTable * pMT)
{
WRAPPER_NO_CONTRACT
SUPPORTS_DAC;
if (pMT->IsDynamicStatics())
{
_ASSERTE(GetDomainFile()->GetModule() == pMT->GetModuleForStatics());
return GetDynamicEntryGCStaticsBasePointer(pMT->GetModuleDynamicEntryID(), pMT->GetLoaderAllocator());
}
else
{
return dac_cast<PTR_BYTE>(m_pGCStatics);
}
}
inline PTR_BYTE GetNonGCStaticsBasePointer(MethodTable * pMT)
{
WRAPPER_NO_CONTRACT
SUPPORTS_DAC;
if (pMT->IsDynamicStatics())
{
_ASSERTE(GetDomainFile()->GetModule() == pMT->GetModuleForStatics());
return GetDynamicEntryNonGCStaticsBasePointer(pMT->GetModuleDynamicEntryID(), pMT->GetLoaderAllocator());
}
else
{
return dac_cast<PTR_BYTE>(this);
}
}
inline DynamicClassInfo* GetDynamicClassInfo(DWORD n)
{
LIMITED_METHOD_CONTRACT
SUPPORTS_DAC;
_ASSERTE(m_pDynamicClassTable.Load() && m_aDynamicEntries > n);
dac_cast<PTR_DynamicEntry>(m_pDynamicClassTable[n].m_pDynamicEntry.Load());
return &m_pDynamicClassTable[n];
}
// These helpers can now return null, as the debugger may do queries on a type
// before the calls to PopulateClass happen
inline PTR_BYTE GetDynamicEntryGCStaticsBasePointer(DWORD n, PTR_LoaderAllocator pLoaderAllocator)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
SO_TOLERANT;
MODE_COOPERATIVE;
SUPPORTS_DAC;
}
CONTRACTL_END;
if (n >= m_aDynamicEntries)
{
return NULL;
}
DynamicClassInfo* pClassInfo = GetDynamicClassInfo(n);
if (!pClassInfo->m_pDynamicEntry)
{
return NULL;
}
PTR_BYTE retval = NULL;
GET_DYNAMICENTRY_GCSTATICS_BASEPOINTER(pLoaderAllocator, pClassInfo, &retval);
return retval;
}
inline PTR_BYTE GetDynamicEntryNonGCStaticsBasePointer(DWORD n, PTR_LoaderAllocator pLoaderAllocator)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
SO_TOLERANT;
MODE_COOPERATIVE;
SUPPORTS_DAC;
}
CONTRACTL_END;
if (n >= m_aDynamicEntries)
{
return NULL;
}
DynamicClassInfo* pClassInfo = GetDynamicClassInfo(n);
if (!pClassInfo->m_pDynamicEntry)
{
return NULL;
}
PTR_BYTE retval = NULL;
GET_DYNAMICENTRY_NONGCSTATICS_BASEPOINTER(pLoaderAllocator, pClassInfo, &retval);
return retval;
}
FORCEINLINE PTR_DynamicClassInfo GetDynamicClassInfoIfInitialized(DWORD n)
{
WRAPPER_NO_CONTRACT;
// m_aDynamicEntries is set last, it needs to be checked first
if (n >= m_aDynamicEntries)
{
return NULL;
}
_ASSERTE(m_pDynamicClassTable.Load() != NULL);
PTR_DynamicClassInfo pDynamicClassInfo = (PTR_DynamicClassInfo)(m_pDynamicClassTable.Load() + n);
// INITIALIZED_FLAG is set last, it needs to be checked first
if ((pDynamicClassInfo->m_dwFlags & ClassInitFlags::INITIALIZED_FLAG) == 0)
{
return NULL;
}
PREFIX_ASSUME(pDynamicClassInfo != NULL);
return pDynamicClassInfo;
}
// iClassIndex is slightly expensive to compute, so if we already know
// it, we can use this helper
inline BOOL IsClassInitialized(MethodTable* pMT, DWORD iClassIndex = (DWORD)-1)
{
WRAPPER_NO_CONTRACT;
return (GetClassFlags(pMT, iClassIndex) & ClassInitFlags::INITIALIZED_FLAG) != 0;
}
inline BOOL IsPrecomputedClassInitialized(DWORD classID)
{
return GetPrecomputedStaticsClassData()[classID] & ClassInitFlags::INITIALIZED_FLAG;
}
inline BOOL IsClassAllocated(MethodTable* pMT, DWORD iClassIndex = (DWORD)-1)
{
WRAPPER_NO_CONTRACT;
return (GetClassFlags(pMT, iClassIndex) & ClassInitFlags::ALLOCATECLASS_FLAG) != 0;
}
BOOL IsClassInitError(MethodTable* pMT, DWORD iClassIndex = (DWORD)-1)
{
WRAPPER_NO_CONTRACT;
return (GetClassFlags(pMT, iClassIndex) & ClassInitFlags::ERROR_FLAG) != 0;
}
void SetClassInitialized(MethodTable* pMT);
void SetClassInitError(MethodTable* pMT);
void EnsureDynamicClassIndex(DWORD dwID);
void AllocateDynamicClass(MethodTable *pMT);
void PopulateClass(MethodTable *pMT);
#ifdef DACCESS_COMPILE
void EnumMemoryRegions(CLRDataEnumMemoryFlags flags);
#endif
static DWORD OffsetOfDataBlob()
{
LIMITED_METHOD_CONTRACT;
return offsetof(DomainLocalModule, m_pDataBlob);
}
FORCEINLINE MethodTable * GetMethodTableFromClassDomainID(DWORD dwClassDomainID)
{
DWORD rid = (DWORD)(dwClassDomainID) + 1;
TypeHandle th = GetDomainFile()->GetModule()->LookupTypeDef(TokenFromRid(rid, mdtTypeDef));
_ASSERTE(!th.IsNull());
MethodTable * pMT = th.AsMethodTable();
PREFIX_ASSUME(pMT != NULL);
return pMT;
}
private:
friend void EmitFastGetSharedStaticBase(CPUSTUBLINKER *psl, CodeLabel *init, bool bCCtorCheck);
void SetClassFlags(MethodTable* pMT, DWORD dwFlags);
DWORD GetClassFlags(MethodTable* pMT, DWORD iClassIndex);
PTR_DomainFile m_pDomainFile;
VolatilePtr<DynamicClassInfo, PTR_DynamicClassInfo> m_pDynamicClassTable; // used for generics and reflection.emit in memory
Volatile<SIZE_T> m_aDynamicEntries; // number of entries in dynamic table
VolatilePtr<UMEntryThunk> m_pADThunkTable;
PTR_OBJECTREF m_pGCStatics; // Handle to GC statics of the module
// In addition to storing the ModuleIndex in the Module class, we also
// keep a copy of the ModuleIndex in the DomainLocalModule class. This
// allows the thread static JIT helpers to quickly convert a pointer to
// a DomainLocalModule into a ModuleIndex.
ModuleIndex m_ModuleIndex;
// Note that the static offset calculation in code:Module::BuildStaticsOffsets takes the offset m_pDataBlob
// into consideration for alignment so we do not need any padding to ensure that the start of the data blob is aligned
BYTE m_pDataBlob[0]; // First byte of the statics blob
// Layout of m_pDataBlob is:
// ClassInit bytes (hold flags for cctor run, cctor error, etc)
// Non GC Statics
public:
// The Module class need to be able to initialized ModuleIndex,
// so for now I will make it a friend..
friend class Module;
FORCEINLINE ModuleIndex GetModuleIndex()
{
LIMITED_METHOD_DAC_CONTRACT;
return m_ModuleIndex;
}
}; // struct DomainLocalModule
typedef DPTR(class DomainLocalBlock) PTR_DomainLocalBlock;
class DomainLocalBlock
{
friend class ClrDataAccess;
friend class CheckAsmOffsets;
private:
PTR_AppDomain m_pDomain;
DPTR(PTR_DomainLocalModule) m_pModuleSlots;
SIZE_T m_aModuleIndices; // Module entries the shared block has allocated
public: // used by code generators
static SIZE_T GetOffsetOfModuleSlotsPointer() { return offsetof(DomainLocalBlock, m_pModuleSlots);}
public:
#ifndef DACCESS_COMPILE
DomainLocalBlock()
: m_pDomain(NULL), m_pModuleSlots(NULL), m_aModuleIndices(0) {}
void EnsureModuleIndex(ModuleIndex index);
void Init(AppDomain *pDomain) { LIMITED_METHOD_CONTRACT; m_pDomain = pDomain; }
#endif
void SetModuleSlot(ModuleIndex index, PTR_DomainLocalModule pLocalModule);
FORCEINLINE PTR_DomainLocalModule GetModuleSlot(ModuleIndex index)
{
WRAPPER_NO_CONTRACT;
SUPPORTS_DAC;
_ASSERTE(index.m_dwIndex < m_aModuleIndices);
return m_pModuleSlots[index.m_dwIndex];
}
inline PTR_DomainLocalModule GetModuleSlot(MethodTable* pMT)
{
WRAPPER_NO_CONTRACT;
return GetModuleSlot(pMT->GetModuleForStatics()->GetModuleIndex());
}
DomainFile* TryGetDomainFile(ModuleIndex index)
{
WRAPPER_NO_CONTRACT;
SUPPORTS_DAC;
// the publishing of m_aModuleIndices and m_pModuleSlots is dependent
// on the order of accesses; we must ensure that we read from m_aModuleIndices
// before m_pModuleSlots.
if (index.m_dwIndex < m_aModuleIndices)
{
MemoryBarrier();
if (m_pModuleSlots[index.m_dwIndex])
{
return m_pModuleSlots[index.m_dwIndex]->GetDomainFile();
}
}
return NULL;
}
DomainFile* GetDomainFile(SIZE_T ModuleID)
{
WRAPPER_NO_CONTRACT;
ModuleIndex index = Module::IDToIndex(ModuleID);
_ASSERTE(index.m_dwIndex < m_aModuleIndices);
return m_pModuleSlots[index.m_dwIndex]->GetDomainFile();
}
#ifndef DACCESS_COMPILE
void SetDomainFile(ModuleIndex index, DomainFile* pDomainFile)
{
WRAPPER_NO_CONTRACT;
_ASSERTE(index.m_dwIndex < m_aModuleIndices);
m_pModuleSlots[index.m_dwIndex]->SetDomainFile(pDomainFile);
}
#endif
#ifdef DACCESS_COMPILE
void EnumMemoryRegions(CLRDataEnumMemoryFlags flags);
#endif
private:
//
// Low level routines to get & set class entries
//
};
#ifdef _MSC_VER
#pragma warning(pop)
#endif
// The large heap handle bucket class is used to contain handles allocated
// from an array contained in the large heap.
class LargeHeapHandleBucket
{
public:
// Constructor and desctructor.
LargeHeapHandleBucket(LargeHeapHandleBucket *pNext, DWORD Size, BaseDomain *pDomain, BOOL bCrossAD = FALSE);
~LargeHeapHandleBucket();
// This returns the next bucket.
LargeHeapHandleBucket *GetNext()
{
LIMITED_METHOD_CONTRACT;
return m_pNext;
}
// This returns the number of remaining handle slots.
DWORD GetNumRemainingHandles()
{
LIMITED_METHOD_CONTRACT;
return m_ArraySize - m_CurrentPos;
}
void ConsumeRemaining()
{
LIMITED_METHOD_CONTRACT;
m_CurrentPos = m_ArraySize;
}
OBJECTREF *TryAllocateEmbeddedFreeHandle();
// Allocate handles from the bucket.
OBJECTREF* AllocateHandles(DWORD nRequested);
OBJECTREF* CurrentPos()
{
LIMITED_METHOD_CONTRACT;
return m_pArrayDataPtr + m_CurrentPos;
}
private:
LargeHeapHandleBucket *m_pNext;
int m_ArraySize;
int m_CurrentPos;
int m_CurrentEmbeddedFreePos;
OBJECTHANDLE m_hndHandleArray;
OBJECTREF *m_pArrayDataPtr;
};
// The large heap handle table is used to allocate handles that are pointers
// to objects stored in an array in the large object heap.
class LargeHeapHandleTable
{
public:
// Constructor and desctructor.
LargeHeapHandleTable(BaseDomain *pDomain, DWORD InitialBucketSize);
~LargeHeapHandleTable();
// Allocate handles from the large heap handle table.
OBJECTREF* AllocateHandles(DWORD nRequested, BOOL bCrossAD = FALSE);
// Release object handles allocated using AllocateHandles().
void ReleaseHandles(OBJECTREF *pObjRef, DWORD nReleased);
private:
// The buckets of object handles.
LargeHeapHandleBucket *m_pHead;
// We need to know the containing domain so we know where to allocate handles
BaseDomain *m_pDomain;
// The size of the LargeHeapHandleBuckets.
DWORD m_NextBucketSize;
// for finding and re-using embedded free items in the list
LargeHeapHandleBucket *m_pFreeSearchHint;
DWORD m_cEmbeddedFree;
#ifdef _DEBUG
// these functions are present to enforce that there is a locking mechanism in place
// for each LargeHeapHandleTable even though the code itself does not do the locking
// you must tell the table which lock you intend to use and it will verify that it has
// in fact been taken before performing any operations
public:
void RegisterCrstDebug(CrstBase *pCrst)
{
LIMITED_METHOD_CONTRACT;
// this function must be called exactly once
_ASSERTE(pCrst != NULL);
_ASSERTE(m_pCrstDebug == NULL);
m_pCrstDebug = pCrst;
}
private:
// we will assert that this Crst is held before using the object
CrstBase *m_pCrstDebug;
#endif
};
class LargeHeapHandleBlockHolder;
void LargeHeapHandleBlockHolder__StaticFree(LargeHeapHandleBlockHolder*);
class LargeHeapHandleBlockHolder:public Holder<LargeHeapHandleBlockHolder*,DoNothing,LargeHeapHandleBlockHolder__StaticFree>
{
LargeHeapHandleTable* m_pTable;
DWORD m_Count;
OBJECTREF* m_Data;
public:
FORCEINLINE LargeHeapHandleBlockHolder(LargeHeapHandleTable* pOwner, DWORD nCount)
{
WRAPPER_NO_CONTRACT;
m_Data = pOwner->AllocateHandles(nCount);
m_Count=nCount;
m_pTable=pOwner;
};
FORCEINLINE void FreeData()
{
WRAPPER_NO_CONTRACT;
for (DWORD i=0;i< m_Count;i++)
ClearObjectReference(m_Data+i);
m_pTable->ReleaseHandles(m_Data, m_Count);
};
FORCEINLINE OBJECTREF* operator[] (DWORD idx)
{
LIMITED_METHOD_CONTRACT;
_ASSERTE(idx<m_Count);
return &(m_Data[idx]);
}
};
FORCEINLINE void LargeHeapHandleBlockHolder__StaticFree(LargeHeapHandleBlockHolder* pHolder)
{
WRAPPER_NO_CONTRACT;
pHolder->FreeData();
};
// The large heap handle bucket class is used to contain handles allocated
// from an array contained in the large heap.
class ThreadStaticHandleBucket
{
public:
// Constructor and desctructor.
ThreadStaticHandleBucket(ThreadStaticHandleBucket *pNext, DWORD Size, BaseDomain *pDomain);
~ThreadStaticHandleBucket();
// This returns the next bucket.
ThreadStaticHandleBucket *GetNext()
{
LIMITED_METHOD_CONTRACT;
return m_pNext;
}
// Allocate handles from the bucket.
OBJECTHANDLE GetHandles();
private:
ThreadStaticHandleBucket *m_pNext;
int m_ArraySize;
OBJECTHANDLE m_hndHandleArray;
};
// The large heap handle table is used to allocate handles that are pointers
// to objects stored in an array in the large object heap.
class ThreadStaticHandleTable
{
public:
// Constructor and desctructor.
ThreadStaticHandleTable(BaseDomain *pDomain);
~ThreadStaticHandleTable();
// Allocate handles from the large heap handle table.
OBJECTHANDLE AllocateHandles(DWORD nRequested);
private:
// The buckets of object handles.
ThreadStaticHandleBucket *m_pHead;
// We need to know the containing domain so we know where to allocate handles
BaseDomain *m_pDomain;
};
//--------------------------------------------------------------------------------------
// Base class for domains. It provides an abstract way of finding the first assembly and
// for creating assemblies in the the domain. The system domain only has one assembly, it
// contains the classes that are logically shared between domains. All other domains can
// have multiple assemblies. Iteration is done be getting the first assembly and then
// calling the Next() method on the assembly.
//
// The system domain should be as small as possible, it includes object, exceptions, etc.
// which are the basic classes required to load other assemblies. All other classes
// should be loaded into the domain. Of coarse there is a trade off between loading the
// same classes multiple times, requiring all domains to load certain assemblies (working
// set) and being able to specify specific versions.
//
#define LOW_FREQUENCY_HEAP_RESERVE_SIZE (3 * PAGE_SIZE)
#define LOW_FREQUENCY_HEAP_COMMIT_SIZE (1 * PAGE_SIZE)
#define HIGH_FREQUENCY_HEAP_RESERVE_SIZE (10 * PAGE_SIZE)
#define HIGH_FREQUENCY_HEAP_COMMIT_SIZE (1 * PAGE_SIZE)
#define STUB_HEAP_RESERVE_SIZE (3 * PAGE_SIZE)
#define STUB_HEAP_COMMIT_SIZE (1 * PAGE_SIZE)
// --------------------------------------------------------------------------------
// PE File List lock - for creating list locks on PE files
// --------------------------------------------------------------------------------
class PEFileListLock : public ListLock
{
public:
#ifndef DACCESS_COMPILE
ListLockEntry *FindFileLock(PEFile *pFile)
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_FORBID_FAULT;
PRECONDITION(HasLock());
ListLockEntry *pEntry;
for (pEntry = m_pHead;
pEntry != NULL;
pEntry = pEntry->m_pNext)
{
if (((PEFile *)pEntry->m_pData)->Equals(pFile))
{
return pEntry;
}
}
return NULL;
}
#endif // DACCESS_COMPILE
DEBUG_NOINLINE static void HolderEnter(PEFileListLock *pThis) PUB
{
WRAPPER_NO_CONTRACT;
ANNOTATION_SPECIAL_HOLDER_CALLER_NEEDS_DYNAMIC_CONTRACT;
pThis->Enter();
}
DEBUG_NOINLINE static void HolderLeave(PEFileListLock *pThis) PUB
{
WRAPPER_NO_CONTRACT;
ANNOTATION_SPECIAL_HOLDER_CALLER_NEEDS_DYNAMIC_CONTRACT;
pThis->Leave();
}
typedef Wrapper<PEFileListLock*, PEFileListLock::HolderEnter, PEFileListLock::HolderLeave> Holder;
};
typedef PEFileListLock::Holder PEFileListLockHolder;
// Loading infrastructure:
//
// a DomainFile is a file being loaded. Files are loaded in layers to enable loading in the
// presence of dependency loops.
//
// FileLoadLevel describes the various levels available. These are implemented slightly
// differently for assemblies and modules, but the basic structure is the same.
//
// LoadLock and FileLoadLock form the ListLock data structures for files. The FileLoadLock
// is specialized in that it allows taking a lock at a particular level. Basicall any
// thread may obtain the lock at a level at which the file has previously been loaded to, but
// only one thread may obtain the lock at its current level.
//
// The PendingLoadQueue is a per thread data structure which serves two purposes. First, it
// holds a "load limit" which automatically restricts the level of recursive loads to be
// one less than the current load which is preceding. This, together with the AppDomain
// LoadLock level behavior, will prevent any deadlocks from occuring due to circular
// dependencies. (Note that it is important that the loading logic understands this restriction,
// and any given level of loading must deal with the fact that any recursive loads will be partially
// unfulfilled in a specific way.)
//
// The second function is to queue up any unfulfilled load requests for the thread. These
// are then delivered immediately after the current load request is dealt with.
class FileLoadLock : public ListLockEntry
{
private:
FileLoadLevel m_level;
DomainFile *m_pDomainFile;
HRESULT m_cachedHR;
ADID m_AppDomainId;
public:
static FileLoadLock *Create(PEFileListLock *pLock, PEFile *pFile, DomainFile *pDomainFile);
~FileLoadLock();
DomainFile *GetDomainFile();
ADID GetAppDomainId();
FileLoadLevel GetLoadLevel();
// CanAcquire will return FALSE if Acquire will definitely not take the lock due
// to levels or deadlock.
// (Note that there is a race exiting from the function, where Acquire may end
// up not taking the lock anyway if another thread did work in the meantime.)
BOOL CanAcquire(FileLoadLevel targetLevel);
// Acquire will return FALSE and not take the lock if the file
// has already been loaded to the target level. Otherwise,
// it will return TRUE and take the lock.
//
// Note that the taker must release the lock via IncrementLoadLevel.
BOOL Acquire(FileLoadLevel targetLevel);
// CompleteLoadLevel can be called after Acquire returns true
// returns TRUE if it updated load level, FALSE if the level was set already
BOOL CompleteLoadLevel(FileLoadLevel level, BOOL success);
void SetError(Exception *ex);
void AddRef();
UINT32 Release() DAC_EMPTY_RET(0);
private:
FileLoadLock(PEFileListLock *pLock, PEFile *pFile, DomainFile *pDomainFile);
static void HolderLeave(FileLoadLock *pThis);
public:
typedef Wrapper<FileLoadLock *, DoNothing, FileLoadLock::HolderLeave> Holder;
};
typedef FileLoadLock::Holder FileLoadLockHolder;
#ifndef DACCESS_COMPILE
typedef ReleaseHolder<FileLoadLock> FileLoadLockRefHolder;
#endif // DACCESS_COMPILE
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning (disable: 4324) //sometimes 64bit compilers complain about alignment
#endif
class LoadLevelLimiter
{
FileLoadLevel m_currentLevel;
LoadLevelLimiter* m_previousLimit;
BOOL m_bActive;
public:
LoadLevelLimiter()
: m_currentLevel(FILE_ACTIVE),
m_previousLimit(NULL),
m_bActive(FALSE)
{
LIMITED_METHOD_CONTRACT;
}
void Activate()
{
WRAPPER_NO_CONTRACT;
m_previousLimit=GetThread()->GetLoadLevelLimiter();
if(m_previousLimit)
m_currentLevel=m_previousLimit->GetLoadLevel();
GetThread()->SetLoadLevelLimiter(this);
m_bActive=TRUE;
}
void Deactivate()
{
WRAPPER_NO_CONTRACT;
if (m_bActive)
{
GetThread()->SetLoadLevelLimiter(m_previousLimit);
m_bActive=FALSE;
}
}
~LoadLevelLimiter()
{
WRAPPER_NO_CONTRACT;
// PendingLoadQueues are allocated on the stack during a load, and
// shared with all nested loads on the same thread.
// Make sure the thread pointer gets reset after the
// top level queue goes out of scope.
if(m_bActive)
{
Deactivate();
}
}
FileLoadLevel GetLoadLevel()
{
LIMITED_METHOD_CONTRACT;
return m_currentLevel;
}
void SetLoadLevel(FileLoadLevel level)
{
LIMITED_METHOD_CONTRACT;
m_currentLevel = level;
}
};
#ifdef _MSC_VER
#pragma warning (pop) //4324
#endif
#define OVERRIDE_LOAD_LEVEL_LIMIT(newLimit) \
LoadLevelLimiter __newLimit; \
__newLimit.Activate(); \
__newLimit.SetLoadLevel(newLimit);
// A BaseDomain much basic information in a code:AppDomain including
//
// * code:#AppdomainHeaps - Heaps for any data structures that will be freed on appdomain unload
//
class BaseDomain
{
friend class Assembly;
friend class AssemblySpec;
friend class AppDomain;
friend class AppDomainNative;
VPTR_BASE_VTABLE_CLASS(BaseDomain)
VPTR_UNIQUE(VPTR_UNIQUE_BaseDomain)
protected:
// These 2 variables are only used on the AppDomain, but by placing them here
// we reduce the cost of keeping the asmconstants file up to date.
// The creation sequence number of this app domain (starting from 1)
// This ID is generated by the code:SystemDomain::GetNewAppDomainId routine
// The ID are recycled.
//
// see also code:ADID
ADID m_dwId;
DomainLocalBlock m_sDomainLocalBlock;
public:
class AssemblyIterator;
friend class AssemblyIterator;
// Static initialization.
static void Attach();
//****************************************************************************************
//
// Initialization/shutdown routines for every instance of an BaseDomain.
BaseDomain();
virtual ~BaseDomain() {}
void Init();
void Stop();
void Terminate();
// ID to uniquely identify this AppDomain - used by the AppDomain publishing
// service (to publish the list of all appdomains present in the process),
// which in turn is used by, for eg., the debugger (to decide which App-
// Domain(s) to attach to).
// This is also used by Remoting for routing cross-appDomain calls.
ADID GetId (void)
{
LIMITED_METHOD_DAC_CONTRACT;
STATIC_CONTRACT_SO_TOLERANT;
return m_dwId;
}
virtual BOOL IsAppDomain() { LIMITED_METHOD_DAC_CONTRACT; return FALSE; }
virtual BOOL IsSharedDomain() { LIMITED_METHOD_DAC_CONTRACT; return FALSE; }
inline BOOL IsDefaultDomain(); // defined later in this file
virtual PTR_LoaderAllocator GetLoaderAllocator() = 0;
virtual PTR_AppDomain AsAppDomain()
{
LIMITED_METHOD_CONTRACT;
STATIC_CONTRACT_SO_TOLERANT;
_ASSERTE(!"Not an AppDomain");
return NULL;
}
// If one domain is the SharedDomain and one is an AppDomain then
// return the AppDomain, i.e. return the domain with the shorter lifetime
// of the two given domains.
static PTR_BaseDomain ComputeBaseDomain(
BaseDomain *pGenericDefinitionDomain, // the domain that owns the generic type or method
Instantiation classInst, // the type arguments to the type (if any)
Instantiation methodInst = Instantiation()); // the type arguments to the method (if any)
static PTR_BaseDomain ComputeBaseDomain(TypeKey * pTypeKey);
#ifdef FEATURE_COMINTEROP
//****************************************************************************************
//
// This will look up interop data for a method table
//
#ifndef DACCESS_COMPILE
// Returns the data pointer if present, NULL otherwise
InteropMethodTableData *LookupComInteropData(MethodTable *pMT)
{
// Take the lock
CrstHolder holder(&m_InteropDataCrst);
// Lookup
InteropMethodTableData *pData = (InteropMethodTableData*) m_interopDataHash.LookupValue((UPTR) pMT, (LPVOID) NULL);
// Not there...
if (pData == (InteropMethodTableData*) INVALIDENTRY)
return NULL;
// Found it
return pData;
}
// Returns TRUE if successfully inserted, FALSE if this would be a duplicate entry
BOOL InsertComInteropData(MethodTable* pMT, InteropMethodTableData *pData)
{
// We don't keep track of this kind of information for interfaces
_ASSERTE(!pMT->IsInterface());
// Take the lock
CrstHolder holder(&m_InteropDataCrst);
// Check to see that it's not already in there
InteropMethodTableData *pDupData = (InteropMethodTableData*) m_interopDataHash.LookupValue((UPTR) pMT, (LPVOID) NULL);
if (pDupData != (InteropMethodTableData*) INVALIDENTRY)
return FALSE;
// Not in there, so insert
m_interopDataHash.InsertValue((UPTR) pMT, (LPVOID) pData);
// Success
return TRUE;
}
#endif // DACCESS_COMPILE
#endif // FEATURE_COMINTEROP
void SetDisableInterfaceCache()
{
m_fDisableInterfaceCache = TRUE;
}
BOOL GetDisableInterfaceCache()
{
return m_fDisableInterfaceCache;
}
#ifdef FEATURE_COMINTEROP
MngStdInterfacesInfo * GetMngStdInterfacesInfo()
{
LIMITED_METHOD_CONTRACT;
return m_pMngStdInterfacesInfo;
}
PTR_CLRPrivBinderWinRT GetWinRtBinder()
{
return m_pWinRtBinder;
}
#endif // FEATURE_COMINTEROP
//****************************************************************************************
// This method returns marshaling data that the EE uses that is stored on a per app domain
// basis.
EEMarshalingData *GetMarshalingData();
// Deletes marshaling data at shutdown (which contains cached factories that needs to be released)
void DeleteMarshalingData();
#ifdef _DEBUG
BOOL OwnDomainLocalBlockLock()
{
WRAPPER_NO_CONTRACT;
return m_DomainLocalBlockCrst.OwnedByCurrentThread();
}
#endif
//****************************************************************************************
// Get the class init lock. The method is limited to friends because inappropriate use
// will cause deadlocks in the system
ListLock* GetClassInitLock()
{
LIMITED_METHOD_CONTRACT;
return &m_ClassInitLock;
}
ListLock* GetJitLock()
{
LIMITED_METHOD_CONTRACT;
return &m_JITLock;
}
ListLock* GetILStubGenLock()
{
LIMITED_METHOD_CONTRACT;
return &m_ILStubGenLock;
}
STRINGREF *IsStringInterned(STRINGREF *pString);
STRINGREF *GetOrInternString(STRINGREF *pString);
virtual BOOL CanUnload() { LIMITED_METHOD_CONTRACT; return FALSE; } // can never unload BaseDomain
// Returns an array of OBJECTREF* that can be used to store domain specific data.
// Statics and reflection info (Types, MemberInfo,..) are stored this way
// If ppLazyAllocate != 0, allocation will only take place if *ppLazyAllocate != 0 (and the allocation
// will be properly serialized)
OBJECTREF *AllocateObjRefPtrsInLargeTable(int nRequested, OBJECTREF** ppLazyAllocate = NULL, BOOL bCrossAD = FALSE);
#ifdef FEATURE_PREJIT
// Ensures that the file for logging profile data is open (we only open it once)
// return false on failure
static BOOL EnsureNGenLogFileOpen();
#endif
//****************************************************************************************
// Handles
#if !defined(DACCESS_COMPILE) && !defined(CROSSGEN_COMPILE) // needs GetCurrentThreadHomeHeapNumber
OBJECTHANDLE CreateTypedHandle(OBJECTREF object, int type)
{
WRAPPER_NO_CONTRACT;
return ::CreateTypedHandle(m_hHandleTableBucket->pTable[GetCurrentThreadHomeHeapNumber()], object, type);
}
OBJECTHANDLE CreateHandle(OBJECTREF object)
{
WRAPPER_NO_CONTRACT;
CONDITIONAL_CONTRACT_VIOLATION(ModeViolation, object == NULL)
return ::CreateHandle(m_hHandleTableBucket->pTable[GetCurrentThreadHomeHeapNumber()], object);
}
OBJECTHANDLE CreateWeakHandle(OBJECTREF object)
{
WRAPPER_NO_CONTRACT;
return ::CreateWeakHandle(m_hHandleTableBucket->pTable[GetCurrentThreadHomeHeapNumber()], object);
}
OBJECTHANDLE CreateShortWeakHandle(OBJECTREF object)
{
WRAPPER_NO_CONTRACT;
return ::CreateShortWeakHandle(m_hHandleTableBucket->pTable[GetCurrentThreadHomeHeapNumber()], object);
}
OBJECTHANDLE CreateLongWeakHandle(OBJECTREF object)
{
WRAPPER_NO_CONTRACT;
CONDITIONAL_CONTRACT_VIOLATION(ModeViolation, object == NULL)
return ::CreateLongWeakHandle(m_hHandleTableBucket->pTable[GetCurrentThreadHomeHeapNumber()], object);
}
OBJECTHANDLE CreateStrongHandle(OBJECTREF object)
{
WRAPPER_NO_CONTRACT;
return ::CreateStrongHandle(m_hHandleTableBucket->pTable[GetCurrentThreadHomeHeapNumber()], object);
}
OBJECTHANDLE CreatePinningHandle(OBJECTREF object)
{
WRAPPER_NO_CONTRACT;
#if CHECK_APP_DOMAIN_LEAKS
if(IsAppDomain())
object->TryAssignAppDomain((AppDomain*)this,TRUE);
#endif
return ::CreatePinningHandle(m_hHandleTableBucket->pTable[GetCurrentThreadHomeHeapNumber()], object);
}
OBJECTHANDLE CreateSizedRefHandle(OBJECTREF object)
{
WRAPPER_NO_CONTRACT;
OBJECTHANDLE h = ::CreateSizedRefHandle(
m_hHandleTableBucket->pTable[GCHeap::IsServerHeap() ? (m_dwSizedRefHandles % m_iNumberOfProcessors) : GetCurrentThreadHomeHeapNumber()],
object);
InterlockedIncrement((LONG*)&m_dwSizedRefHandles);
return h;
}
#ifdef FEATURE_COMINTEROP
OBJECTHANDLE CreateRefcountedHandle(OBJECTREF object)
{
WRAPPER_NO_CONTRACT;
return ::CreateRefcountedHandle(m_hHandleTableBucket->pTable[GetCurrentThreadHomeHeapNumber()], object);
}
OBJECTHANDLE CreateWinRTWeakHandle(OBJECTREF object, IWeakReference* pWinRTWeakReference)
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
MODE_COOPERATIVE;
}
CONTRACTL_END;
return ::CreateWinRTWeakHandle(m_hHandleTableBucket->pTable[GetCurrentThreadHomeHeapNumber()], object, pWinRTWeakReference);
}
#endif // FEATURE_COMINTEROP
OBJECTHANDLE CreateVariableHandle(OBJECTREF object, UINT type)
{
WRAPPER_NO_CONTRACT;
return ::CreateVariableHandle(m_hHandleTableBucket->pTable[GetCurrentThreadHomeHeapNumber()], object, type);
}
OBJECTHANDLE CreateDependentHandle(OBJECTREF primary, OBJECTREF secondary)
{
WRAPPER_NO_CONTRACT;
return ::CreateDependentHandle(m_hHandleTableBucket->pTable[GetCurrentThreadHomeHeapNumber()], primary, secondary);
}
#endif // DACCESS_COMPILE && !CROSSGEN_COMPILE
BOOL ContainsOBJECTHANDLE(OBJECTHANDLE handle);
#ifdef FEATURE_FUSION
IApplicationContext *GetFusionContext() {LIMITED_METHOD_CONTRACT; return m_pFusionContext; }
#else
IUnknown *GetFusionContext() {LIMITED_METHOD_CONTRACT; return m_pFusionContext; }
#if defined(FEATURE_HOST_ASSEMBLY_RESOLVER)
CLRPrivBinderCoreCLR *GetTPABinderContext() {LIMITED_METHOD_CONTRACT; return m_pTPABinderContext; }
#endif // defined(FEATURE_HOST_ASSEMBLY_RESOLVER)
#endif
CrstExplicitInit * GetLoaderAllocatorReferencesLock()
{
LIMITED_METHOD_CONTRACT;
return &m_crstLoaderAllocatorReferences;
}
protected:
//****************************************************************************************
// Helper method to initialize the large heap handle table.
void InitLargeHeapHandleTable();
//****************************************************************************************
// Adds an assembly to the domain.
void AddAssemblyNoLock(Assembly* assem);
//****************************************************************************************
//
// Hash table that maps a MethodTable to COM Interop compatibility data.
PtrHashMap m_interopDataHash;
// Critical sections & locks
PEFileListLock m_FileLoadLock; // Protects the list of assemblies in the domain
CrstExplicitInit m_DomainCrst; // General Protection for the Domain
CrstExplicitInit m_DomainCacheCrst; // Protects the Assembly and Unmanaged caches
CrstExplicitInit m_DomainLocalBlockCrst;
CrstExplicitInit m_InteropDataCrst; // Used for COM Interop compatiblilty
// Used to protect the reference lists in the collectible loader allocators attached to this appdomain
CrstExplicitInit m_crstLoaderAllocatorReferences;
CrstExplicitInit m_WinRTFactoryCacheCrst; // For WinRT factory cache
//#AssemblyListLock
// Used to protect the assembly list. Taken also by GC or debugger thread, therefore we have to avoid
// triggering GC while holding this lock (by switching the thread to GC_NOTRIGGER while it is held).
CrstExplicitInit m_crstAssemblyList;
BOOL m_fDisableInterfaceCache; // RCW COM interface cache
ListLock m_ClassInitLock;
ListLock m_JITLock;
ListLock m_ILStubGenLock;
// Fusion context, used for adding assemblies to the is domain. It defines
// fusion properties for finding assemblyies such as SharedBinPath,
// PrivateBinPath, Application Directory, etc.
#ifdef FEATURE_FUSION
IApplicationContext* m_pFusionContext; // Binding context for the domain
#else
IUnknown *m_pFusionContext; // Current binding context for the domain
#if defined(FEATURE_HOST_ASSEMBLY_RESOLVER)
CLRPrivBinderCoreCLR *m_pTPABinderContext; // Reference to the binding context that holds TPA list details
#endif // defined(FEATURE_HOST_ASSEMBLY_RESOLVER)
#endif
HandleTableBucket *m_hHandleTableBucket;
// The large heap handle table.
LargeHeapHandleTable *m_pLargeHeapHandleTable;
// The large heap handle table critical section.
CrstExplicitInit m_LargeHeapHandleTableCrst;
EEMarshalingData *m_pMarshalingData;
#ifdef FEATURE_COMINTEROP
// Information regarding the managed standard interfaces.
MngStdInterfacesInfo *m_pMngStdInterfacesInfo;
// WinRT binder (only in classic = non-AppX; AppX has the WinRT binder inside code:CLRPrivBinderAppX)
PTR_CLRPrivBinderWinRT m_pWinRtBinder;
#endif // FEATURE_COMINTEROP
// Number of allocated slots for context local statics of this domain
DWORD m_dwContextStatics;
// Protects allocation of slot IDs for thread and context statics
static CrstStatic m_SpecialStaticsCrst;
public:
// Lazily allocate offset for context static
DWORD AllocateContextStaticsOffset(DWORD* pOffsetSlot);
public:
// Only call this routine when you can guarantee there are no
// loads in progress.
void ClearFusionContext();
public:
//****************************************************************************************
// Synchronization holders.
class LockHolder : public CrstHolder
{
public:
LockHolder(BaseDomain *pD)
: CrstHolder(&pD->m_DomainCrst)
{
WRAPPER_NO_CONTRACT;
}
};
friend class LockHolder;
class CacheLockHolder : public CrstHolder
{
public:
CacheLockHolder(BaseDomain *pD)
: CrstHolder(&pD->m_DomainCacheCrst)
{
WRAPPER_NO_CONTRACT;
}
};
friend class CacheLockHolder;
class DomainLocalBlockLockHolder : public CrstHolder
{
public:
DomainLocalBlockLockHolder(BaseDomain *pD)
: CrstHolder(&pD->m_DomainLocalBlockCrst)
{
WRAPPER_NO_CONTRACT;
}
};
friend class DomainLocalBlockLockHolder;
class LoadLockHolder : public PEFileListLockHolder
{
public:
LoadLockHolder(BaseDomain *pD, BOOL Take = TRUE)
: PEFileListLockHolder(&pD->m_FileLoadLock, Take)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
CAN_TAKE_LOCK;
}
CONTRACTL_END;
}
};
friend class LoadLockHolder;
class WinRTFactoryCacheLockHolder : public CrstHolder
{
public:
WinRTFactoryCacheLockHolder(BaseDomain *pD)
: CrstHolder(&pD->m_WinRTFactoryCacheCrst)
{
WRAPPER_NO_CONTRACT;
}
};
friend class WinRTFactoryCacheLockHolder;
public:
void InitVSD();
RangeList *GetCollectibleVSDRanges() { return &m_collVSDRanges; }
private:
TypeIDMap m_typeIDMap;
// Range list for collectible types. Maps VSD PCODEs back to the VirtualCallStubManager they belong to
LockedRangeList m_collVSDRanges;
public:
UINT32 GetTypeID(PTR_MethodTable pMT);
UINT32 LookupTypeID(PTR_MethodTable pMT);
PTR_MethodTable LookupType(UINT32 id);
private:
// I have yet to figure out an efficent way to get the number of handles
// of a particular type that's currently used by the process without
// spending more time looking at the handle table code. We know that
// our only customer (asp.net) in Dev10 is not going to create many of
// these handles so I am taking a shortcut for now and keep the sizedref
// handle count on the AD itself.
DWORD m_dwSizedRefHandles;
static int m_iNumberOfProcessors;
public:
// Called by DestroySizedRefHandle
void DecNumSizedRefHandles()
{
WRAPPER_NO_CONTRACT;
LONG result;
result = InterlockedDecrement((LONG*)&m_dwSizedRefHandles);
_ASSERTE(result >= 0);
}
DWORD GetNumSizedRefHandles()
{
return m_dwSizedRefHandles;
}
// Profiler rejit
private:
ReJitManager m_reJitMgr;
public:
ReJitManager * GetReJitManager() { return &m_reJitMgr; }
#ifdef DACCESS_COMPILE
public:
virtual void EnumMemoryRegions(CLRDataEnumMemoryFlags flags,
bool enumThis);
#endif
#ifdef FEATURE_CORECLR
public:
enum AppDomainCompatMode
{
APPDOMAINCOMPAT_NONE
#ifdef FEATURE_LEGACYNETCF
, APPDOMAINCOMPAT_APP_EARLIER_THAN_WP8 // for "AppDomainCompatSwitch" == "WindowsPhone_3.7.0.0" or "AppDomainCompatSwitch" == "WindowsPhone_3.8.0.0"
#endif
};
void SetAppDomainCompatMode(AppDomainCompatMode compatMode);
AppDomainCompatMode GetAppDomainCompatMode();
private:
AppDomainCompatMode m_CompatMode;
#endif // FEATURE_CORECLR
}; // class BaseDomain
enum
{
ATTACH_ASSEMBLY_LOAD = 0x1,
ATTACH_MODULE_LOAD = 0x2,
ATTACH_CLASS_LOAD = 0x4,
ATTACH_ALL = 0x7
};
class ADUnloadSink
{
protected:
~ADUnloadSink();
CLREvent m_UnloadCompleteEvent;
HRESULT m_UnloadResult;
Volatile<LONG> m_cRef;
public:
ADUnloadSink();
void ReportUnloadResult (HRESULT hr, OBJECTREF* pException);
void WaitUnloadCompletion();
HRESULT GetUnloadResult() {LIMITED_METHOD_CONTRACT; return m_UnloadResult;};
void Reset();
ULONG AddRef();
ULONG Release();
};
FORCEINLINE void ADUnloadSink__Release(ADUnloadSink* pADSink)
{
WRAPPER_NO_CONTRACT;
if (pADSink)
pADSink->Release();
}
typedef Wrapper <ADUnloadSink*,DoNothing,ADUnloadSink__Release,NULL> ADUnloadSinkHolder;
// This filters the output of IterateAssemblies. This ought to be declared more locally
// but it would result in really verbose callsites.
//
// Assemblies can be categorized by their load status (loaded, loading, or loaded just
// enough that they would be made available to profilers)
// Independently, they can also be categorized as execution or introspection.
//
// An assembly will be included in the results of IterateAssemblies only if
// the appropriate bit is set for *both* characterizations.
//
// The flags can be combined so if you want all loaded assemblies, you must specify:
//
/// kIncludeLoaded|kIncludeExecution|kIncludeIntrospection
enum AssemblyIterationFlags
{
// load status flags
kIncludeLoaded = 0x00000001, // include assemblies that are already loaded
// (m_level >= code:FILE_LOAD_DELIVER_EVENTS)
kIncludeLoading = 0x00000002, // include assemblies that are still in the process of loading
// (all m_level values)
kIncludeAvailableToProfilers
= 0x00000020, // include assemblies available to profilers
// See comment at code:DomainFile::IsAvailableToProfilers
// Execution / introspection flags
kIncludeExecution = 0x00000004, // include assemblies that are loaded for execution only
kIncludeIntrospection = 0x00000008, // include assemblies that are loaded for introspection only
kIncludeFailedToLoad = 0x00000010, // include assemblies that failed to load
// Collectible assemblies flags
kExcludeCollectible = 0x00000040, // Exclude all collectible assemblies
kIncludeCollected = 0x00000080,
// Include assemblies which were collected and cannot be referenced anymore. Such assemblies are not
// AddRef-ed. Any manipulation with them should be protected by code:GetAssemblyListLock.
// Should be used only by code:LoaderAllocator::GCLoaderAllocators.
}; // enum AssemblyIterationFlags
//---------------------------------------------------------------------------------------
//
// Base class for holder code:CollectibleAssemblyHolder (see code:HolderBase).
// Manages AddRef/Release for collectible assemblies. It is no-op for 'normal' non-collectible assemblies.
//
// Each type of type parameter needs 2 methods implemented:
// code:CollectibleAssemblyHolderBase::GetLoaderAllocator
// code:CollectibleAssemblyHolderBase::IsCollectible
//
template<typename _Type>
class CollectibleAssemblyHolderBase
{
protected:
_Type m_value;
public:
CollectibleAssemblyHolderBase(const _Type & value = NULL)
{
LIMITED_METHOD_CONTRACT;
m_value = value;
}
void DoAcquire()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
// We don't need to keep the assembly alive in DAC - see code:#CAH_DAC
#ifndef DACCESS_COMPILE
if (this->IsCollectible(m_value))
{
LoaderAllocator * pLoaderAllocator = GetLoaderAllocator(m_value);
pLoaderAllocator->AddReference();
}
#endif //!DACCESS_COMPILE
}
void DoRelease()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
#ifndef DACCESS_COMPILE
if (this->IsCollectible(m_value))
{
LoaderAllocator * pLoaderAllocator = GetLoaderAllocator(m_value);
pLoaderAllocator->Release();
}
#endif //!DACCESS_COMPILE
}
private:
LoaderAllocator * GetLoaderAllocator(DomainAssembly * pDomainAssembly)
{
WRAPPER_NO_CONTRACT;
return pDomainAssembly->GetLoaderAllocator();
}
BOOL IsCollectible(DomainAssembly * pDomainAssembly)
{
WRAPPER_NO_CONTRACT;
return pDomainAssembly->IsCollectible();
}
LoaderAllocator * GetLoaderAllocator(Assembly * pAssembly)
{
WRAPPER_NO_CONTRACT;
return pAssembly->GetLoaderAllocator();
}
BOOL IsCollectible(Assembly * pAssembly)
{
WRAPPER_NO_CONTRACT;
return pAssembly->IsCollectible();
}
}; // class CollectibleAssemblyHolderBase<>
//---------------------------------------------------------------------------------------
//
// Holder of assembly reference which keeps collectible assembly alive while the holder is valid.
//
// Collectible assembly can be collected at any point when GC happens. Almost instantly all native data
// structures of the assembly (e.g. code:DomainAssembly, code:Assembly) could be deallocated.
// Therefore any usage of (collectible) assembly data structures from native world, has to prevent the
// deallocation by increasing ref-count on the assembly / associated loader allocator.
//
// #CAH_DAC
// In DAC we don't AddRef/Release as the assembly doesn't have to be kept alive: The process is stopped when
// DAC is used and therefore the assembly cannot just disappear.
//
template<typename _Type>
class CollectibleAssemblyHolder : public BaseWrapper<_Type, CollectibleAssemblyHolderBase<_Type> >
{
public:
FORCEINLINE
CollectibleAssemblyHolder(const _Type & value = NULL, BOOL fTake = TRUE)
: BaseWrapper<_Type, CollectibleAssemblyHolderBase<_Type> >(value, fTake)
{
STATIC_CONTRACT_WRAPPER;
}
FORCEINLINE
CollectibleAssemblyHolder &
operator=(const _Type & value)
{
STATIC_CONTRACT_WRAPPER;
BaseWrapper<_Type, CollectibleAssemblyHolderBase<_Type> >::operator=(value);
return *this;
}
// Operator & is overloaded in parent, therefore we have to get to 'this' pointer explicitly.
FORCEINLINE
CollectibleAssemblyHolder<_Type> *
This()
{
LIMITED_METHOD_CONTRACT;
return this;
}
}; // class CollectibleAssemblyHolder<>
//---------------------------------------------------------------------------------------
//
#ifdef FEATURE_LOADER_OPTIMIZATION
class SharedAssemblyLocator
{
public:
enum
{
DOMAINASSEMBLY = 1,
PEASSEMBLY = 2,
PEASSEMBLYEXACT = 3
};
DWORD GetType() {LIMITED_METHOD_CONTRACT; return m_type;};
#ifndef DACCESS_COMPILE
DomainAssembly* GetDomainAssembly() {LIMITED_METHOD_CONTRACT; _ASSERTE(m_type==DOMAINASSEMBLY); return (DomainAssembly*)m_value;};
PEAssembly* GetPEAssembly() {LIMITED_METHOD_CONTRACT; _ASSERTE(m_type==PEASSEMBLY||m_type==PEASSEMBLYEXACT); return (PEAssembly*)m_value;};
SharedAssemblyLocator(DomainAssembly* pAssembly)
{
LIMITED_METHOD_CONTRACT;
m_type=DOMAINASSEMBLY;
m_value=pAssembly;
}
SharedAssemblyLocator(PEAssembly* pFile, DWORD type = PEASSEMBLY)
{
LIMITED_METHOD_CONTRACT;
m_type = type;
m_value = pFile;
}
#endif // DACCESS_COMPILE
DWORD Hash();
protected:
DWORD m_type;
LPVOID m_value;
#if FEATURE_VERSIONING
ULONG m_uIdentityHash;
#endif
};
#endif // FEATURE_LOADER_OPTIMIZATION
//
// Stores binding information about failed assembly loads for DAC
//
struct FailedAssembly {
SString displayName;
SString location;
#ifdef FEATURE_FUSION
LOADCTX_TYPE context;
#endif
HRESULT error;
void Initialize(AssemblySpec *pSpec, Exception *ex)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
}
CONTRACTL_END;
displayName.SetASCII(pSpec->GetName());
location.Set(pSpec->GetCodeBase());
error = ex->GetHR();
//
// Determine the binding context assembly would have been in.
// If the parent has been set, use its binding context.
// If the parent hasn't been set but the code base has, use LoadFrom.
// Otherwise, use the default.
//
#ifdef FEATURE_FUSION
context = pSpec->GetParentIAssembly() ? pSpec->GetParentIAssembly()->GetFusionLoadContext() : LOADCTX_TYPE_LOADFROM;
#endif // FEATURE_FUSION
}
};
#ifdef FEATURE_COMINTEROP
// Cache used by COM Interop
struct NameToTypeMapEntry
{
// Host space representation of the key
struct Key
{
LPCWSTR m_wzName; // The type name or registry string representation of the GUID "{<guid>}"
SIZE_T m_cchName; // wcslen(m_wzName) for faster hashtable lookup
};
struct DacKey
{
PTR_CWSTR m_wzName; // The type name or registry string representation of the GUID "{<guid>}"
SIZE_T m_cchName; // wcslen(m_wzName) for faster hashtable lookup
} m_key;
TypeHandle m_typeHandle; // Using TypeHandle instead of MethodTable* to avoid losing information when sharing method tables.
UINT m_nEpoch; // tracks creation Epoch. This is incremented each time an external reader enumerate the cache
BYTE m_bFlags;
};
typedef DPTR(NameToTypeMapEntry) PTR_NameToTypeMapEntry;
class NameToTypeMapTraits : public NoRemoveSHashTraits< DefaultSHashTraits<NameToTypeMapEntry> >
{
public:
typedef NameToTypeMapEntry::Key key_t;
static const NameToTypeMapEntry Null() { NameToTypeMapEntry e; e.m_key.m_wzName = NULL; e.m_key.m_cchName = 0; return e; }
static bool IsNull(const NameToTypeMapEntry &e) { return e.m_key.m_wzName == NULL; }
static const key_t GetKey(const NameToTypeMapEntry &e)
{
key_t key;
key.m_wzName = (LPCWSTR)(e.m_key.m_wzName); // this cast brings the string over to the host, in a DAC build
key.m_cchName = e.m_key.m_cchName;
return key;
}
static count_t Hash(const key_t &key) { WRAPPER_NO_CONTRACT; return HashStringN(key.m_wzName, key.m_cchName); }
static BOOL Equals(const key_t &lhs, const key_t &rhs)
{
WRAPPER_NO_CONTRACT;
return (lhs.m_cchName == rhs.m_cchName) && memcmp(lhs.m_wzName, rhs.m_wzName, lhs.m_cchName * sizeof(WCHAR)) == 0;
}
void OnDestructPerEntryCleanupAction(const NameToTypeMapEntry& e)
{
WRAPPER_NO_CONTRACT;
_ASSERTE(e.m_key.m_cchName == wcslen(e.m_key.m_wzName));
#ifndef DACCESS_COMPILE
delete [] e.m_key.m_wzName;
#endif // DACCESS_COMPILE
}
static const bool s_DestructPerEntryCleanupAction = true;
};
typedef SHash<NameToTypeMapTraits> NameToTypeMapTable;
typedef DPTR(NameToTypeMapTable) PTR_NameToTypeMapTable;
struct WinRTFactoryCacheEntry
{
typedef MethodTable *Key;
Key key; // Type as KEY
CtxEntry *m_pCtxEntry; // Context entry - used to verify whether the cache is a match
OBJECTHANDLE m_ohFactoryObject; // Handle to factory object
};
class WinRTFactoryCacheTraits : public DefaultSHashTraits<WinRTFactoryCacheEntry>
{
public:
typedef WinRTFactoryCacheEntry::Key key_t;
static const WinRTFactoryCacheEntry Null() { WinRTFactoryCacheEntry e; e.key = NULL; return e; }
static bool IsNull(const WinRTFactoryCacheEntry &e) { return e.key == NULL; }
static const WinRTFactoryCacheEntry::Key GetKey(const WinRTFactoryCacheEntry& e) { return e.key; }
static count_t Hash(WinRTFactoryCacheEntry::Key key) { return (count_t)((size_t)key); }
static BOOL Equals(WinRTFactoryCacheEntry::Key lhs, WinRTFactoryCacheEntry::Key rhs)
{ return lhs == rhs; }
static const WinRTFactoryCacheEntry Deleted() { WinRTFactoryCacheEntry e; e.key = (MethodTable *)-1; return e; }
static bool IsDeleted(const WinRTFactoryCacheEntry &e) { return e.key == (MethodTable *)-1; }
static void OnDestructPerEntryCleanupAction(const WinRTFactoryCacheEntry& e);
static const bool s_DestructPerEntryCleanupAction = true;
};
typedef SHash<WinRTFactoryCacheTraits> WinRTFactoryCache;
#endif // FEATURE_COMINTEROP
class AppDomainIterator;
const DWORD DefaultADID = 1;
template <class AppDomainType> class AppDomainCreationHolder;
// An Appdomain is the managed equivalent of a process. It is an isolation unit (conceptually you don't
// have pointers directly from one appdomain to another, but rather go through remoting proxies). It is
// also a unit of unloading.
//
// Threads are always running in the context of a particular AppDomain. See
// file:threads.h#RuntimeThreadLocals for more details.
//
// see code:BaseDomain for much of the meat of a AppDomain (heaps locks, etc)
// * code:AppDomain.m_Assemblies - is a list of code:Assembly in the appdomain
//
class AppDomain : public BaseDomain
{
friend class ADUnloadSink;
friend class SystemDomain;
friend class AssemblySink;
friend class AppDomainNative;
friend class AssemblyNative;
friend class AssemblySpec;
friend class ClassLoader;
friend class ThreadNative;
friend class RCWCache;
friend class ClrDataAccess;
friend class CheckAsmOffsets;
friend class AppDomainFromIDHolder;
VPTR_VTABLE_CLASS(AppDomain, BaseDomain)
public:
#ifndef DACCESS_COMPILE
AppDomain();
virtual ~AppDomain();
#endif
static void DoADUnloadWork();
DomainAssembly* FindDomainAssembly(Assembly*);
void EnterContext(Thread* pThread, Context* pCtx,ContextTransitionFrame *pFrame);
#ifndef DACCESS_COMPILE
//-----------------------------------------------------------------------------------------------------------------
// Convenience wrapper for ::GetAppDomain to provide better encapsulation.
static AppDomain * GetCurrentDomain()
{ return ::GetAppDomain(); }
#endif //!DACCESS_COMPILE
//-----------------------------------------------------------------------------------------------------------------
// Initializes an AppDomain. (this functions is not called from the SystemDomain)
void Init();
// creates only unamaged part
static void CreateUnmanagedObject(AppDomainCreationHolder<AppDomain>& result);
inline void SetAppDomainManagerInfo(LPCWSTR szAssemblyName, LPCWSTR szTypeName, EInitializeNewDomainFlags dwInitializeDomainFlags);
inline BOOL HasAppDomainManagerInfo();
inline LPCWSTR GetAppDomainManagerAsm();
inline LPCWSTR GetAppDomainManagerType();
inline EInitializeNewDomainFlags GetAppDomainManagerInitializeNewDomainFlags();
#ifndef FEATURE_CORECLR
inline BOOL AppDomainManagerSetFromConfig();
Assembly *GetAppDomainManagerEntryAssembly();
void ComputeTargetFrameworkName();
#endif // FEATURE_CORECLR
#if defined(FEATURE_CORECLR) && defined(FEATURE_COMINTEROP)
HRESULT SetWinrtApplicationContext(SString &appLocalWinMD);
#endif // FEATURE_CORECLR && FEATURE_COMINTEROP
BOOL CanReversePInvokeEnter();
void SetReversePInvokeCannotEnter();
bool MustForceTrivialWaitOperations();
void SetForceTrivialWaitOperations();
//****************************************************************************************
//
// Stop deletes all the assemblies but does not remove other resources like
// the critical sections
void Stop();
// Gets rid of resources
void Terminate();
#ifdef FEATURE_PREJIT
//assembly cleanup that requires suspended runtime
void DeleteNativeCodeRanges();
#endif
// final assembly cleanup
void ShutdownAssemblies();
void ShutdownFreeLoaderAllocators(BOOL bFromManagedCode);
void ReleaseDomainBoundInfo();
void ReleaseFiles();
// Remove the Appdomain for the system and cleans up. This call should not be
// called from shut down code.
void CloseDomain();
virtual BOOL IsAppDomain() { LIMITED_METHOD_DAC_CONTRACT; return TRUE; }
virtual PTR_AppDomain AsAppDomain() { LIMITED_METHOD_CONTRACT; return dac_cast<PTR_AppDomain>(this); }
#ifndef FEATURE_CORECLR
void InitializeSorting(OBJECTREF* ppAppdomainSetup);
void InitializeHashing(OBJECTREF* ppAppdomainSetup);
#endif
OBJECTREF DoSetup(OBJECTREF* setupInfo);
OBJECTREF GetExposedObject();
OBJECTREF GetRawExposedObject() {
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
SO_TOLERANT;
MODE_COOPERATIVE;
}
CONTRACTL_END;
if (m_ExposedObject) {
return ObjectFromHandle(m_ExposedObject);
}
else {
return NULL;
}
}
OBJECTHANDLE GetRawExposedObjectHandleForDebugger() { LIMITED_METHOD_DAC_CONTRACT; return m_ExposedObject; }
#ifdef FEATURE_COMINTEROP
HRESULT GetComIPForExposedObject(IUnknown **pComIP);
MethodTable *GetRedirectedType(WinMDAdapter::RedirectedTypeIndex index);
#endif // FEATURE_COMINTEROP
//****************************************************************************************
protected:
// Multi-thread safe access to the list of assemblies
class DomainAssemblyList
{
private:
ArrayList m_array;
#ifdef _DEBUG
AppDomain * dbg_m_pAppDomain;
public:
void Debug_SetAppDomain(AppDomain * pAppDomain)
{
dbg_m_pAppDomain = pAppDomain;
}
#endif //_DEBUG
public:
bool IsEmpty()
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
} CONTRACTL_END;
// This function can be reliably called without taking the lock, because the first assembly
// added to the arraylist is non-collectible, and the ArrayList itself allows lockless read access
return (m_array.GetCount() == 0);
}
void Clear(AppDomain * pAppDomain)
{
CONTRACTL {
NOTHROW;
WRAPPER(GC_TRIGGERS); // Triggers only in MODE_COOPERATIVE (by taking the lock)
MODE_ANY;
} CONTRACTL_END;
_ASSERTE(dbg_m_pAppDomain == pAppDomain);
CrstHolder ch(pAppDomain->GetAssemblyListLock());
m_array.Clear();
}
DWORD GetCount(AppDomain * pAppDomain)
{
CONTRACTL {
NOTHROW;
WRAPPER(GC_TRIGGERS); // Triggers only in MODE_COOPERATIVE (by taking the lock)
MODE_ANY;
} CONTRACTL_END;
_ASSERTE(dbg_m_pAppDomain == pAppDomain);
CrstHolder ch(pAppDomain->GetAssemblyListLock());
return GetCount_Unlocked();
}
DWORD GetCount_Unlocked()
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
} CONTRACTL_END;
#ifndef DACCESS_COMPILE
_ASSERTE(dbg_m_pAppDomain->GetAssemblyListLock()->OwnedByCurrentThread());
#endif
// code:Append_Unlock guarantees that we do not have more than MAXDWORD items
return m_array.GetCount();
}
void Get(AppDomain * pAppDomain, DWORD index, CollectibleAssemblyHolder<DomainAssembly *> * pAssemblyHolder)
{
CONTRACTL {
NOTHROW;
WRAPPER(GC_TRIGGERS); // Triggers only in MODE_COOPERATIVE (by taking the lock)
MODE_ANY;
} CONTRACTL_END;
_ASSERTE(dbg_m_pAppDomain == pAppDomain);
CrstHolder ch(pAppDomain->GetAssemblyListLock());
Get_Unlocked(index, pAssemblyHolder);
}
void Get_Unlocked(DWORD index, CollectibleAssemblyHolder<DomainAssembly *> * pAssemblyHolder)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
} CONTRACTL_END;
_ASSERTE(dbg_m_pAppDomain->GetAssemblyListLock()->OwnedByCurrentThread());
*pAssemblyHolder = dac_cast<PTR_DomainAssembly>(m_array.Get(index));
}
// Doesn't lock the assembly list (caller has to hold the lock already).
// Doesn't AddRef the returned assembly (if collectible).
DomainAssembly * Get_UnlockedNoReference(DWORD index)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
SUPPORTS_DAC;
} CONTRACTL_END;
#ifndef DACCESS_COMPILE
_ASSERTE(dbg_m_pAppDomain->GetAssemblyListLock()->OwnedByCurrentThread());
#endif
return dac_cast<PTR_DomainAssembly>(m_array.Get(index));
}
#ifndef DACCESS_COMPILE
void Set(AppDomain * pAppDomain, DWORD index, DomainAssembly * pAssembly)
{
CONTRACTL {
NOTHROW;
WRAPPER(GC_TRIGGERS); // Triggers only in MODE_COOPERATIVE (by taking the lock)
MODE_ANY;
} CONTRACTL_END;
_ASSERTE(dbg_m_pAppDomain == pAppDomain);
CrstHolder ch(pAppDomain->GetAssemblyListLock());
return Set_Unlocked(index, pAssembly);
}
void Set_Unlocked(DWORD index, DomainAssembly * pAssembly)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
} CONTRACTL_END;
_ASSERTE(dbg_m_pAppDomain->GetAssemblyListLock()->OwnedByCurrentThread());
m_array.Set(index, pAssembly);
}
HRESULT Append_Unlocked(DomainAssembly * pAssembly)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
} CONTRACTL_END;
_ASSERTE(dbg_m_pAppDomain->GetAssemblyListLock()->OwnedByCurrentThread());
return m_array.Append(pAssembly);
}
#else //DACCESS_COMPILE
void
EnumMemoryRegions(CLRDataEnumMemoryFlags flags)
{
SUPPORTS_DAC;
m_array.EnumMemoryRegions(flags);
}
#endif // DACCESS_COMPILE
// Should be used only by code:AssemblyIterator::Create
ArrayList::Iterator GetArrayListIterator()
{
return m_array.Iterate();
}
}; // class DomainAssemblyList
// Conceptually a list of code:Assembly structures, protected by lock code:GetAssemblyListLock
DomainAssemblyList m_Assemblies;
public:
// Note that this lock switches thread into GC_NOTRIGGER region as GC can take it too.
CrstExplicitInit * GetAssemblyListLock()
{
LIMITED_METHOD_CONTRACT;
return &m_crstAssemblyList;
}
public:
class AssemblyIterator
{
// AppDomain context with the assembly list
AppDomain * m_pAppDomain;
ArrayList::Iterator m_Iterator;
AssemblyIterationFlags m_assemblyIterationFlags;
public:
BOOL Next(CollectibleAssemblyHolder<DomainAssembly *> * pDomainAssemblyHolder);
// Note: Does not lock the assembly list, but AddRefs collectible assemblies.
BOOL Next_Unlocked(CollectibleAssemblyHolder<DomainAssembly *> * pDomainAssemblyHolder);
#ifndef DACCESS_COMPILE
private:
// Can be called only from AppDomain shutdown code:AppDomain::ShutdownAssemblies.
// Note: Does not lock the assembly list and does not AddRefs collectible assemblies.
BOOL Next_UnsafeNoAddRef(DomainAssembly ** ppDomainAssembly);
#endif
private:
inline DWORD GetIndex()
{
LIMITED_METHOD_CONTRACT;
return m_Iterator.GetIndex();
}
private:
friend class AppDomain;
// Cannot have constructor so this iterator can be used inside a union
static AssemblyIterator Create(AppDomain * pAppDomain, AssemblyIterationFlags assemblyIterationFlags)
{
LIMITED_METHOD_CONTRACT;
AssemblyIterator i;
i.m_pAppDomain = pAppDomain;
i.m_Iterator = pAppDomain->m_Assemblies.GetArrayListIterator();
i.m_assemblyIterationFlags = assemblyIterationFlags;
return i;
}
}; // class AssemblyIterator
AssemblyIterator IterateAssembliesEx(AssemblyIterationFlags assemblyIterationFlags)
{
LIMITED_METHOD_CONTRACT;
return AssemblyIterator::Create(this, assemblyIterationFlags);
}
#ifdef FEATURE_CORECLR
private:
struct NativeImageDependenciesEntry
{
BaseAssemblySpec m_AssemblySpec;
GUID m_guidMVID;
};
class NativeImageDependenciesTraits : public NoRemoveSHashTraits<DefaultSHashTraits<NativeImageDependenciesEntry *> >
{
public:
typedef BaseAssemblySpec *key_t;
static key_t GetKey(NativeImageDependenciesEntry * e) { return &(e->m_AssemblySpec); }
static count_t Hash(key_t k)
{
return k->Hash();
}
static BOOL Equals(key_t lhs, key_t rhs)
{
return lhs->CompareEx(rhs);
}
};
SHash<NativeImageDependenciesTraits> m_NativeImageDependencies;
public:
void CheckForMismatchedNativeImages(AssemblySpec * pSpec, const GUID * pGuid);
public:
class PathIterator
{
friend class AppDomain;
ArrayList::Iterator m_i;
public:
BOOL Next()
{
WRAPPER_NO_CONTRACT;
return m_i.Next();
}
SString* GetPath()
{
WRAPPER_NO_CONTRACT;
return dac_cast<PTR_SString>(m_i.GetElement());
}
};
BOOL BindingByManifestFile();
PathIterator IterateNativeDllSearchDirectories();
void SetNativeDllSearchDirectories(LPCWSTR paths);
BOOL HasNativeDllSearchDirectories();
void ShutdownNativeDllSearchDirectories();
#endif // FEATURE_CORECLR
public:
SIZE_T GetAssemblyCount()
{
WRAPPER_NO_CONTRACT;
return m_Assemblies.GetCount(this);
}
CHECK CheckCanLoadTypes(Assembly *pAssembly);
CHECK CheckCanExecuteManagedCode(MethodDesc* pMD);
CHECK CheckLoading(DomainFile *pFile, FileLoadLevel level);
FileLoadLevel GetDomainFileLoadLevel(DomainFile *pFile);
BOOL IsLoading(DomainFile *pFile, FileLoadLevel level);
static FileLoadLevel GetThreadFileLoadLevel();
void LoadDomainFile(DomainFile *pFile,
FileLoadLevel targetLevel);
enum FindAssemblyOptions
{
FindAssemblyOptions_None = 0x0,
FindAssemblyOptions_IncludeFailedToLoad = 0x1
};
DomainAssembly * FindAssembly(PEAssembly * pFile, FindAssemblyOptions options = FindAssemblyOptions_None) DAC_EMPTY_RET(NULL);
#ifdef FEATURE_MIXEDMODE
// Finds only loaded modules, elevates level if needed
Module* GetIJWModule(HMODULE hMod) DAC_EMPTY_RET(NULL);
// Finds loading modules
DomainFile* FindIJWDomainFile(HMODULE hMod, const SString &path) DAC_EMPTY_RET(NULL);
#endif // FEATURE_MIXEDMODE
Assembly *LoadAssembly(AssemblySpec* pIdentity,
PEAssembly *pFile,
FileLoadLevel targetLevel,
AssemblyLoadSecurity *pLoadSecurity = NULL);
// this function does not provide caching, you must use LoadDomainAssembly
// unless the call is guaranteed to succeed or you don't need the caching
// (e.g. if you will FailFast or tear down the AppDomain anyway)
// The main point that you should not bypass caching if you might try to load the same file again,
// resulting in multiple DomainAssembly objects that share the same PEAssembly for ngen image
//which is violating our internal assumptions
DomainAssembly *LoadDomainAssemblyInternal( AssemblySpec* pIdentity,
PEAssembly *pFile,
FileLoadLevel targetLevel,
AssemblyLoadSecurity *pLoadSecurity = NULL);
DomainAssembly *LoadDomainAssembly( AssemblySpec* pIdentity,
PEAssembly *pFile,
FileLoadLevel targetLevel,
AssemblyLoadSecurity *pLoadSecurity = NULL);
#ifdef FEATURE_MULTIMODULE_ASSEMBLIES
DomainModule *LoadDomainModule(DomainAssembly *pAssembly,
PEModule *pFile,
FileLoadLevel targetLevel);
#endif
CHECK CheckValidModule(Module *pModule);
#ifdef FEATURE_LOADER_OPTIMIZATION
DomainFile *LoadDomainNeutralModuleDependency(Module *pModule, FileLoadLevel targetLevel);
#endif
#ifdef FEATURE_FUSION
PEAssembly *BindExplicitAssembly(HMODULE hMod, BOOL bindable);
Assembly *LoadExplicitAssembly(HMODULE hMod, BOOL bindable);
void GetFileFromFusion(IAssembly *pIAssembly, LPCWSTR wszModuleName,
SString &path);
#endif
// private:
void LoadSystemAssemblies();
DomainFile *LoadDomainFile(FileLoadLock *pLock,
FileLoadLevel targetLevel);
void TryIncrementalLoad(DomainFile *pFile, FileLoadLevel workLevel, FileLoadLockHolder &lockHolder);
Assembly *LoadAssemblyHelper(LPCWSTR wszAssembly,
LPCWSTR wszCodeBase);
#ifndef DACCESS_COMPILE // needs AssemblySpec
//****************************************************************************************
// Returns and Inserts assemblies into a lookup cache based on the binding information
// in the AssemblySpec. There can be many AssemblySpecs to a single assembly.
DomainAssembly* FindCachedAssembly(AssemblySpec* pSpec, BOOL fThrow=TRUE)
{
WRAPPER_NO_CONTRACT;
return m_AssemblyCache.LookupAssembly(pSpec, fThrow);
}
PEAssembly* FindCachedFile(AssemblySpec* pSpec, BOOL fThrow = TRUE);
BOOL IsCached(AssemblySpec *pSpec);
#endif // DACCESS_COMPILE
void CacheStringsForDAC();
BOOL AddFileToCache(AssemblySpec* pSpec, PEAssembly *pFile, BOOL fAllowFailure = FALSE);
BOOL AddAssemblyToCache(AssemblySpec* pSpec, DomainAssembly *pAssembly);
BOOL AddExceptionToCache(AssemblySpec* pSpec, Exception *ex);
void AddUnmanagedImageToCache(LPCWSTR libraryName, HMODULE hMod);
HMODULE FindUnmanagedImageInCache(LPCWSTR libraryName);
//****************************************************************************************
//
// Adds an assembly to the domain.
void AddAssembly(DomainAssembly * assem);
void RemoveAssembly_Unlocked(DomainAssembly * pAsm);
BOOL ContainsAssembly(Assembly * assem);
#ifdef FEATURE_LOADER_OPTIMIZATION
enum SharePolicy
{
// Attributes to control when to use domain neutral assemblies
SHARE_POLICY_UNSPECIFIED, // Use the current default policy (LoaderOptimization.NotSpecified)
SHARE_POLICY_NEVER, // Do not share anything, except the system assembly (LoaderOptimization.SingleDomain)
SHARE_POLICY_ALWAYS, // Share everything possible (LoaderOptimization.MultiDomain)
SHARE_POLICY_GAC, // Share only GAC-bound assemblies (LoaderOptimization.MultiDomainHost)
SHARE_POLICY_COUNT,
SHARE_POLICY_MASK = 0x3,
// NOTE that previously defined was a bit 0x40 which might be set on this value
// in custom attributes.
SHARE_POLICY_DEFAULT = SHARE_POLICY_NEVER,
};
void SetSharePolicy(SharePolicy policy);
SharePolicy GetSharePolicy();
BOOL ReduceSharePolicyFromAlways();
//****************************************************************************************
// Determines if the image is to be loaded into the shared assembly or an individual
// appdomains.
#ifndef FEATURE_CORECLR
BOOL ApplySharePolicy(DomainAssembly *pFile);
BOOL ApplySharePolicyFlag(DomainAssembly *pFile);
#endif
#endif // FEATURE_LOADER_OPTIMIZATION
BOOL HasSetSecurityPolicy();
FORCEINLINE IApplicationSecurityDescriptor* GetSecurityDescriptor()
{
LIMITED_METHOD_CONTRACT;
STATIC_CONTRACT_SO_TOLERANT;
return static_cast<IApplicationSecurityDescriptor*>(m_pSecDesc);
}
void CreateSecurityDescriptor();
//****************************************************************************************
//
// Reference count. When an appdomain is first created the reference is bump
// to one when it is added to the list of domains (see SystemDomain). An explicit
// Removal from the list is necessary before it will be deleted.
ULONG AddRef(void);
ULONG Release(void) DAC_EMPTY_RET(0);
//****************************************************************************************
LPCWSTR GetFriendlyName(BOOL fDebuggerCares = TRUE);
LPCWSTR GetFriendlyNameForDebugger();
LPCWSTR GetFriendlyNameForLogging();
#ifdef DACCESS_COMPILE
PVOID GetFriendlyNameNoSet(bool* isUtf8);
#endif
void SetFriendlyName(LPCWSTR pwzFriendlyName, BOOL fDebuggerCares = TRUE);
void ResetFriendlyName(BOOL fDebuggerCares = TRUE);
//****************************************************************************************
// This can be used to override the binding behavior of the appdomain. It
// is overridden in the compilation domain. It is important that all
// static binding goes through this path.
virtual PEAssembly * BindAssemblySpec(
AssemblySpec *pSpec,
BOOL fThrowOnFileNotFound,
BOOL fRaisePrebindEvents,
StackCrawlMark *pCallerStackMark = NULL,
AssemblyLoadSecurity *pLoadSecurity = NULL,
BOOL fUseHostBinderIfAvailable = TRUE) DAC_EMPTY_RET(NULL);
#ifdef FEATURE_HOSTED_BINDER
HRESULT BindAssemblySpecForHostedBinder(
AssemblySpec * pSpec,
IAssemblyName * pAssemblyName,
ICLRPrivBinder * pBinder,
PEAssembly ** ppAssembly) DAC_EMPTY_RET(E_FAIL);
HRESULT BindHostedPrivAssembly(
PEAssembly * pParentPEAssembly,
ICLRPrivAssembly * pPrivAssembly,
IAssemblyName * pAssemblyName,
PEAssembly ** ppAssembly,
BOOL fIsIntrospectionOnly = FALSE) DAC_EMPTY_RET(S_OK);
#endif // FEATURE_HOSTED_BINDER
#ifdef FEATURE_REFLECTION_ONLY_LOAD
virtual DomainAssembly *BindAssemblySpecForIntrospectionDependencies(AssemblySpec *pSpec) DAC_EMPTY_RET(NULL);
#endif
PEAssembly *TryResolveAssembly(AssemblySpec *pSpec, BOOL fPreBind);
// Store a successful binding into the cache. This will keep the file from
// being physically unmapped, as well as shortcutting future attempts to bind
// the same spec throught the Cached entry point.
//
// Right now we only cache assembly binds for "probing" type
// binding situations, basically when loading domain neutral assemblies or
// zap files.
//
// <TODO>@todo: We may want to be more aggressive about this if
// there are other situations where we are repeatedly binding the
// same assembly specs, though.</TODO>
//
// Returns TRUE if stored
// FALSE if it's a duplicate (caller should clean up args)
BOOL StoreBindAssemblySpecResult(AssemblySpec *pSpec,
PEAssembly *pFile,
BOOL clone = TRUE);
BOOL StoreBindAssemblySpecError(AssemblySpec *pSpec,
HRESULT hr,
OBJECTREF *pThrowable,
BOOL clone = TRUE);
//****************************************************************************************
//
#ifdef FEATURE_FUSION
static BOOL SetContextProperty(IApplicationContext* pFusionContext,
LPCWSTR pProperty,
OBJECTREF* obj);
#endif
//****************************************************************************************
//
// Uses the first assembly to add an application base to the Context. This is done
// in a lazy fashion so executables do not take the perf hit unless the load other
// assemblies
#ifdef FEATURE_FUSION
LPWSTR GetDynamicDir();
#endif
#ifndef DACCESS_COMPILE
void OnAssemblyLoad(Assembly *assem);
void OnAssemblyLoadUnlocked(Assembly *assem);
static BOOL OnUnhandledException(OBJECTREF *pThrowable, BOOL isTerminating = TRUE);
#endif
// True iff a debugger is attached to the process (same as CORDebuggerAttached)
BOOL IsDebuggerAttached (void);
#ifdef DEBUGGING_SUPPORTED
// Notify debugger of all assemblies, modules, and possibly classes in this AppDomain
BOOL NotifyDebuggerLoad(int flags, BOOL attaching);
// Send unload notifications to the debugger for all assemblies, modules and classes in this AppDomain
void NotifyDebuggerUnload();
#endif // DEBUGGING_SUPPORTED
void SetSystemAssemblyLoadEventSent (BOOL fFlag);
BOOL WasSystemAssemblyLoadEventSent (void);
#ifndef DACCESS_COMPILE
OBJECTREF* AllocateStaticFieldObjRefPtrs(int nRequested, OBJECTREF** ppLazyAllocate = NULL)
{
WRAPPER_NO_CONTRACT;
return AllocateObjRefPtrsInLargeTable(nRequested, ppLazyAllocate);
}
OBJECTREF* AllocateStaticFieldObjRefPtrsCrossDomain(int nRequested, OBJECTREF** ppLazyAllocate = NULL)
{
WRAPPER_NO_CONTRACT;
return AllocateObjRefPtrsInLargeTable(nRequested, ppLazyAllocate, TRUE);
}
#endif // DACCESS_COMPILE
void EnumStaticGCRefs(promote_func* fn, ScanContext* sc);
DomainLocalBlock *GetDomainLocalBlock()
{
LIMITED_METHOD_DAC_CONTRACT;
return &m_sDomainLocalBlock;
}
static SIZE_T GetOffsetOfModuleSlotsPointer()
{
WRAPPER_NO_CONTRACT;
return offsetof(AppDomain,m_sDomainLocalBlock) + DomainLocalBlock::GetOffsetOfModuleSlotsPointer();
}
void SetupSharedStatics();
ADUnloadSink* PrepareForWaitUnloadCompletion();
//****************************************************************************************
//
// Create a quick lookup for classes loaded into this domain based on their GUID.
//
void InsertClassForCLSID(MethodTable* pMT, BOOL fForceInsert = FALSE);
void InsertClassForCLSID(MethodTable* pMT, GUID *pGuid);
#ifdef FEATURE_COMINTEROP
private:
void CacheTypeByNameWorker(const SString &ssClassName, const UINT vCacheVersion, TypeHandle typeHandle, BYTE flags, BOOL bReplaceExisting = FALSE);
TypeHandle LookupTypeByNameWorker(const SString &ssClassName, UINT *pvCacheVersion, BYTE *pbFlags);
public:
// Used by COM Interop for mapping WinRT runtime class names to real types.
void CacheTypeByName(const SString &ssClassName, const UINT vCacheVersion, TypeHandle typeHandle, BYTE flags, BOOL bReplaceExisting = FALSE);
TypeHandle LookupTypeByName(const SString &ssClassName, UINT *pvCacheVersion, BYTE *pbFlags);
PTR_MethodTable LookupTypeByGuid(const GUID & guid);
#ifndef DACCESS_COMPILE
inline BOOL CanCacheWinRTTypeByGuid(TypeHandle typeHandle)
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
// Only allow caching guid/types maps for types loaded during
// "normal" domain operation
if (IsCompilationDomain() || (m_Stage < STAGE_OPEN))
return FALSE;
MethodTable *pMT = typeHandle.GetMethodTable();
if (pMT != NULL)
{
// Don't cache mscorlib-internal declarations of WinRT types.
if (pMT->GetModule()->IsSystem() && pMT->IsProjectedFromWinRT())
return FALSE;
// Don't cache redirected WinRT types.
if (WinRTTypeNameConverter::IsRedirectedWinRTSourceType(pMT))
return FALSE;
}
return TRUE;
}
#endif // !DACCESS_COMPILE
void CacheWinRTTypeByGuid(TypeHandle typeHandle);
void GetCachedWinRTTypes(SArray<PTR_MethodTable> * pTypes, SArray<GUID> * pGuids, UINT minEpoch, UINT * pCurEpoch);
// Used by COM Interop for caching WinRT factory objects.
void CacheWinRTFactoryObject(MethodTable *pClassMT, OBJECTREF *refFactory, LPVOID lpCtxCookie);
OBJECTREF LookupWinRTFactoryObject(MethodTable *pClassMT, LPVOID lpCtxCookie);
void RemoveWinRTFactoryObjects(LPVOID pCtxCookie);
MethodTable *LoadCOMClass(GUID clsid, BOOL bLoadRecord = FALSE, BOOL* pfAssemblyInReg = NULL);
COMorRemotingFlag GetComOrRemotingFlag();
BOOL GetPreferComInsteadOfManagedRemoting();
OBJECTREF GetMissingObject(); // DispatchInfo will call function to retrieve the Missing.Value object.
#endif // FEATURE_COMINTEROP
#ifndef DACCESS_COMPILE
MethodTable* LookupClass(REFIID iid)
{
WRAPPER_NO_CONTRACT;
MethodTable *pMT = (MethodTable*) m_clsidHash.LookupValue((UPTR) GetKeyFromGUID(&iid), (LPVOID)&iid);
return (pMT == (MethodTable*) INVALIDENTRY
? NULL
: pMT);
}
#endif // DACCESS_COMPILE
//<TODO>@todo get a better key</TODO>
ULONG GetKeyFromGUID(const GUID *pguid)
{
LIMITED_METHOD_CONTRACT;
return *(ULONG *) pguid;
}
#ifdef FEATURE_COMINTEROP
ComCallWrapperCache* GetComCallWrapperCache();
RCWCache *GetRCWCache()
{
WRAPPER_NO_CONTRACT;
if (m_pRCWCache)
return m_pRCWCache;
// By separating the cache creation from the common lookup, we
// can keep the (x86) EH prolog/epilog off the path.
return CreateRCWCache();
}
private:
RCWCache *CreateRCWCache();
public:
RCWCache *GetRCWCacheNoCreate()
{
LIMITED_METHOD_CONTRACT;
return m_pRCWCache;
}
RCWRefCache *GetRCWRefCache();
void ResetComCallWrapperCache()
{
LIMITED_METHOD_CONTRACT;
m_pComCallWrapperCache = NULL;
}
MethodTable* GetLicenseInteropHelperMethodTable();
#endif // FEATURE_COMINTEROP
//****************************************************************************************
// Get the proxy for this app domain
#ifdef FEATURE_REMOTING
OBJECTREF GetAppDomainProxy();
#endif
ADIndex GetIndex()
{
LIMITED_METHOD_CONTRACT;
SUPPORTS_DAC;
return m_dwIndex;
}
TPIndex GetTPIndex()
{
LIMITED_METHOD_CONTRACT;
return m_tpIndex;
}
void InitializeDomainContext(BOOL allowRedirects, LPCWSTR pwszPath, LPCWSTR pwszConfig);
#ifdef FEATURE_FUSION
IApplicationContext *CreateFusionContext();
void SetupLoaderOptimization(DWORD optimization);
#endif
#ifdef FEATURE_VERSIONING
IUnknown *CreateFusionContext();
#endif // FEATURE_VERSIONING
#if defined(FEATURE_HOST_ASSEMBLY_RESOLVER)
void OverrideDefaultContextBinder(IUnknown *pOverrideBinder)
{
LIMITED_METHOD_CONTRACT;
_ASSERTE(pOverrideBinder != NULL);
pOverrideBinder->AddRef();
m_pFusionContext->Release();
m_pFusionContext = pOverrideBinder;
}
#endif // defined(FEATURE_HOST_ASSEMBLY_RESOLVER)
#ifdef FEATURE_PREJIT
CorCompileConfigFlags GetNativeConfigFlags();
#endif // FEATURE_PREJIT
//****************************************************************************************
// Create a domain context rooted at the fileName. The directory containing the file name
// is the application base and the configuration file is the fileName appended with
// .config. If no name is passed in then no domain is created.
static AppDomain* CreateDomainContext(LPCWSTR fileName);
// Sets up the current domain's fusion context based on the given exe file name
// (app base & config file)
void SetupExecutableFusionContext(LPCWSTR exePath);
//****************************************************************************************
// Manage a pool of asyncrhonous objects used to fetch assemblies. When a sink is released
// it places itself back on the pool list. Only one object is kept in the pool.
#ifdef FEATURE_FUSION
AssemblySink* AllocateAssemblySink(AssemblySpec* pSpec);
#endif
void SetIsUserCreatedDomain()
{
LIMITED_METHOD_CONTRACT;
m_dwFlags |= USER_CREATED_DOMAIN;
}
BOOL IsUserCreatedDomain()
{
LIMITED_METHOD_CONTRACT;
return (m_dwFlags & USER_CREATED_DOMAIN);
}
void SetIgnoreUnhandledExceptions()
{
LIMITED_METHOD_CONTRACT;
m_dwFlags |= IGNORE_UNHANDLED_EXCEPTIONS;
}
BOOL IgnoreUnhandledExceptions()
{
LIMITED_METHOD_CONTRACT;
return (m_dwFlags & IGNORE_UNHANDLED_EXCEPTIONS);
}
#if defined(FEATURE_CORECLR)
void SetEnablePInvokeAndClassicComInterop()
{
LIMITED_METHOD_CONTRACT;
m_dwFlags |= ENABLE_PINVOKE_AND_CLASSIC_COMINTEROP;
}
BOOL EnablePInvokeAndClassicComInterop()
{
LIMITED_METHOD_CONTRACT;
return (m_dwFlags & ENABLE_PINVOKE_AND_CLASSIC_COMINTEROP);
}
void SetAllowPlatformSpecificAppAssemblies()
{
LIMITED_METHOD_CONTRACT;
m_dwFlags |= ENABLE_SKIP_PLAT_CHECKS;
}
BOOL AllowPlatformSpecificAppAssemblies()
{
LIMITED_METHOD_CONTRACT;
if(IsCompilationDomain())
return TRUE;
return (m_dwFlags & ENABLE_SKIP_PLAT_CHECKS);
}
void SetAllowLoadFile()
{
LIMITED_METHOD_CONTRACT;
m_dwFlags |= ENABLE_ASSEMBLY_LOADFILE;
}
BOOL IsLoadFileAllowed()
{
LIMITED_METHOD_CONTRACT;
return (m_dwFlags & ENABLE_ASSEMBLY_LOADFILE);
}
void DisableTransparencyEnforcement()
{
LIMITED_METHOD_CONTRACT;
m_dwFlags |= DISABLE_TRANSPARENCY_ENFORCEMENT;
}
BOOL IsTransparencyEnforcementDisabled()
{
LIMITED_METHOD_CONTRACT;
return (m_dwFlags & DISABLE_TRANSPARENCY_ENFORCEMENT);
}
#endif // defined(FEATURE_CORECLR)
void SetPassiveDomain()
{
LIMITED_METHOD_CONTRACT;
m_dwFlags |= PASSIVE_DOMAIN;
}
BOOL IsPassiveDomain()
{
LIMITED_METHOD_CONTRACT;
return (m_dwFlags & PASSIVE_DOMAIN);
}
void SetVerificationDomain()
{
LIMITED_METHOD_CONTRACT;
m_dwFlags |= VERIFICATION_DOMAIN;
}
BOOL IsVerificationDomain()
{
LIMITED_METHOD_CONTRACT;
return (m_dwFlags & VERIFICATION_DOMAIN);
}
void SetIllegalVerificationDomain()
{
LIMITED_METHOD_CONTRACT;
m_dwFlags |= ILLEGAL_VERIFICATION_DOMAIN;
}
BOOL IsIllegalVerificationDomain()
{
LIMITED_METHOD_CONTRACT;
return (m_dwFlags & ILLEGAL_VERIFICATION_DOMAIN);
}
void SetCompilationDomain()
{
LIMITED_METHOD_CONTRACT;
m_dwFlags |= (PASSIVE_DOMAIN|COMPILATION_DOMAIN);
}
BOOL IsCompilationDomain();
PTR_CompilationDomain ToCompilationDomain()
{
LIMITED_METHOD_CONTRACT;
_ASSERTE(IsCompilationDomain());
return dac_cast<PTR_CompilationDomain>(this);
}
void SetCanUnload()
{
LIMITED_METHOD_CONTRACT;
m_dwFlags |= APP_DOMAIN_CAN_BE_UNLOADED;
}
BOOL CanUnload()
{
LIMITED_METHOD_CONTRACT;
STATIC_CONTRACT_SO_TOLERANT;
return m_dwFlags & APP_DOMAIN_CAN_BE_UNLOADED;
}
void SetRemotingConfigured()
{
LIMITED_METHOD_CONTRACT;
STATIC_CONTRACT_SO_TOLERANT;
FastInterlockOr((ULONG*)&m_dwFlags, REMOTING_CONFIGURED_FOR_DOMAIN);
}
BOOL IsRemotingConfigured()
{
LIMITED_METHOD_CONTRACT;
STATIC_CONTRACT_SO_TOLERANT;
return m_dwFlags & REMOTING_CONFIGURED_FOR_DOMAIN;
}
void SetOrphanedLocks()
{
LIMITED_METHOD_CONTRACT;
STATIC_CONTRACT_SO_TOLERANT;
FastInterlockOr((ULONG*)&m_dwFlags, ORPHANED_LOCKS);
}
BOOL HasOrphanedLocks()
{
LIMITED_METHOD_CONTRACT;
STATIC_CONTRACT_SO_TOLERANT;
return m_dwFlags & ORPHANED_LOCKS;
}
// This function is used to relax asserts in the lock accounting.
// It returns true if we are fine with hosed lock accounting in this domain.
BOOL OkToIgnoreOrphanedLocks()
{
WRAPPER_NO_CONTRACT;
return HasOrphanedLocks() && m_Stage >= STAGE_UNLOAD_REQUESTED;
}
static void ExceptionUnwind(Frame *pFrame);
#ifdef _DEBUG
void TrackADThreadEnter(Thread *pThread, Frame *pFrame);
void TrackADThreadExit(Thread *pThread, Frame *pFrame);
void DumpADThreadTrack();
#endif
#ifndef DACCESS_COMPILE
void ThreadEnter(Thread *pThread, Frame *pFrame)
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
#ifdef _DEBUG
if (LoggingOn(LF_APPDOMAIN, LL_INFO100))
TrackADThreadEnter(pThread, pFrame);
else
#endif
{
InterlockedIncrement((LONG*)&m_dwThreadEnterCount);
LOG((LF_APPDOMAIN, LL_INFO1000, "AppDomain::ThreadEnter %p to [%d] (%8.8x) %S count %d\n",
pThread,GetId().m_dwId, this,
GetFriendlyNameForLogging(),GetThreadEnterCount()));
#if _DEBUG_AD_UNLOAD
printf("AppDomain::ThreadEnter %p to [%d] (%8.8x) %S count %d\n",
pThread, GetId().m_dwId, this,
GetFriendlyNameForLogging(), GetThreadEnterCount());
#endif
}
}
void ThreadExit(Thread *pThread, Frame *pFrame)
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
#ifdef _DEBUG
if (LoggingOn(LF_APPDOMAIN, LL_INFO100)) {
TrackADThreadExit(pThread, pFrame);
}
else
#endif
{
LONG result;
result = InterlockedDecrement((LONG*)&m_dwThreadEnterCount);
_ASSERTE(result >= 0);
LOG((LF_APPDOMAIN, LL_INFO1000, "AppDomain::ThreadExit from [%d] (%8.8x) %S count %d\n",
this, GetId().m_dwId,
GetFriendlyNameForLogging(), GetThreadEnterCount()));
#if _DEBUG_ADUNLOAD
printf("AppDomain::ThreadExit %x from [%d] (%8.8x) %S count %d\n",
pThread->GetThreadId(), this, GetId().m_dwId,
GetFriendlyNameForLogging(), GetThreadEnterCount());
#endif
}
}
#endif // DACCESS_COMPILE
ULONG GetThreadEnterCount()
{
LIMITED_METHOD_CONTRACT;
return m_dwThreadEnterCount;
}
BOOL OnlyOneThreadLeft()
{
LIMITED_METHOD_CONTRACT;
return m_dwThreadEnterCount==1 || m_dwThreadsStillInAppDomain ==1;
}
Context *GetDefaultContext()
{
LIMITED_METHOD_CONTRACT;
return m_pDefaultContext;
}
BOOL CanLoadCode()
{
LIMITED_METHOD_CONTRACT;
return m_Stage >= STAGE_READYFORMANAGEDCODE && m_Stage < STAGE_CLOSED;
}
void SetAnonymouslyHostedDynamicMethodsAssembly(DomainAssembly * pDomainAssembly)
{
LIMITED_METHOD_CONTRACT;
_ASSERTE(pDomainAssembly != NULL);
_ASSERTE(m_anonymouslyHostedDynamicMethodsAssembly == NULL);
m_anonymouslyHostedDynamicMethodsAssembly = pDomainAssembly;
}
DomainAssembly * GetAnonymouslyHostedDynamicMethodsAssembly()
{
LIMITED_METHOD_CONTRACT;
return m_anonymouslyHostedDynamicMethodsAssembly;
}
BOOL HasUnloadStarted()
{
LIMITED_METHOD_CONTRACT;
return m_Stage>=STAGE_EXITED;
}
static void RefTakerAcquire(AppDomain* pDomain)
{
WRAPPER_NO_CONTRACT;
if(!pDomain)
return;
pDomain->AddRef();
#ifdef _DEBUG
FastInterlockIncrement(&pDomain->m_dwRefTakers);
#endif
}
static void RefTakerRelease(AppDomain* pDomain)
{
WRAPPER_NO_CONTRACT;
if(!pDomain)
return;
#ifdef _DEBUG
_ASSERTE(pDomain->m_dwRefTakers);
FastInterlockDecrement(&pDomain->m_dwRefTakers);
#endif
pDomain->Release();
}
#ifdef _DEBUG
BOOL IsHeldByIterator()
{
LIMITED_METHOD_CONTRACT;
return m_dwIterHolders>0;
}
BOOL IsHeldByRefTaker()
{
LIMITED_METHOD_CONTRACT;
return m_dwRefTakers>0;
}
void IteratorRelease()
{
LIMITED_METHOD_CONTRACT;
_ASSERTE(m_dwIterHolders);
FastInterlockDecrement(&m_dwIterHolders);
}
void IteratorAcquire()
{
LIMITED_METHOD_CONTRACT;
FastInterlockIncrement(&m_dwIterHolders);
}
#endif
BOOL IsActive()
{
LIMITED_METHOD_DAC_CONTRACT;
return m_Stage >= STAGE_ACTIVE && m_Stage < STAGE_CLOSED;
}
// Range for normal execution of code in the appdomain, currently used for
// appdomain resource monitoring since we don't care to update resource usage
// unless it's in these stages (as fields of AppDomain may not be valid if it's
// not within these stages)
BOOL IsUserActive()
{
LIMITED_METHOD_DAC_CONTRACT;
return m_Stage >= STAGE_ACTIVE && m_Stage <= STAGE_OPEN;
}
BOOL IsValid()
{
LIMITED_METHOD_DAC_CONTRACT;
#ifdef DACCESS_COMPILE
// We want to see all appdomains in SOS, even the about to be destructed ones.
// There is no risk of races under DAC, so we will pretend to be unconditionally valid.
return TRUE;
#else
return m_Stage > STAGE_CREATING && m_Stage < STAGE_CLOSED;
#endif
}
#ifdef _DEBUG
BOOL IsBeingCreated()
{
LIMITED_METHOD_CONTRACT;
return m_dwCreationHolders > 0;
}
void IncCreationCount()
{
LIMITED_METHOD_CONTRACT;
FastInterlockIncrement(&m_dwCreationHolders);
_ASSERTE(m_dwCreationHolders > 0);
}
void DecCreationCount()
{
LIMITED_METHOD_CONTRACT;
FastInterlockDecrement(&m_dwCreationHolders);
_ASSERTE(m_dwCreationHolders > -1);
}
#endif
BOOL IsRunningIn(Thread* pThread);
BOOL IsUnloading()
{
LIMITED_METHOD_CONTRACT;
SUPPORTS_DAC;
return m_Stage > STAGE_UNLOAD_REQUESTED;
}
BOOL NotReadyForManagedCode()
{
LIMITED_METHOD_CONTRACT;
return m_Stage < STAGE_READYFORMANAGEDCODE;
}
void SetFinalized()
{
LIMITED_METHOD_CONTRACT;
SetStage(STAGE_FINALIZED);
}
BOOL IsFinalizing()
{
LIMITED_METHOD_CONTRACT;
return m_Stage >= STAGE_FINALIZING;
}
BOOL IsFinalized()
{
LIMITED_METHOD_CONTRACT;
return m_Stage >= STAGE_FINALIZED;
}
BOOL NoAccessToHandleTable()
{
LIMITED_METHOD_CONTRACT;
SUPPORTS_DAC;
return m_Stage >= STAGE_HANDLETABLE_NOACCESS;
}
// Checks whether the given thread can enter the app domain
BOOL CanThreadEnter(Thread *pThread);
// Following two are needed for the Holder
static void SetUnloadInProgress(AppDomain *pThis) PUB;
static void SetUnloadComplete(AppDomain *pThis) PUB;
// Predicates for GC asserts
BOOL ShouldHaveFinalization()
{
LIMITED_METHOD_CONTRACT;
return ((DWORD) m_Stage) < STAGE_COLLECTED;
}
BOOL ShouldHaveCode()
{
LIMITED_METHOD_CONTRACT;
return ((DWORD) m_Stage) < STAGE_COLLECTED;
}
BOOL ShouldHaveRoots()
{
LIMITED_METHOD_CONTRACT;
return ((DWORD) m_Stage) < STAGE_CLEARED;
}
BOOL ShouldHaveInstances()
{
LIMITED_METHOD_CONTRACT;
return ((DWORD) m_Stage) < STAGE_COLLECTED;
}
static void RaiseExitProcessEvent();
Assembly* RaiseResourceResolveEvent(DomainAssembly* pAssembly, LPCSTR szName);
DomainAssembly* RaiseTypeResolveEventThrowing(DomainAssembly* pAssembly, LPCSTR szName, ASSEMBLYREF *pResultingAssemblyRef);
Assembly* RaiseAssemblyResolveEvent(AssemblySpec *pSpec, BOOL fIntrospection, BOOL fPreBind);
private:
CrstExplicitInit m_ReflectionCrst;
CrstExplicitInit m_RefClassFactCrst;
EEClassFactoryInfoHashTable *m_pRefClassFactHash; // Hash table that maps a class factory info to a COM comp.
#ifdef FEATURE_COMINTEROP
DispIDCache *m_pRefDispIDCache;
COMorRemotingFlag m_COMorRemotingFlag;
OBJECTHANDLE m_hndMissing; //Handle points to Missing.Value Object which is used for [Optional] arg scenario during IDispatch CCW Call
MethodTable* m_rpCLRTypes[WinMDAdapter::RedirectedTypeIndex_Count];
MethodTable* LoadRedirectedType(WinMDAdapter::RedirectedTypeIndex index, WinMDAdapter::FrameworkAssemblyIndex assembly);
#endif // FEATURE_COMINTEROP
public:
CrstBase *GetRefClassFactCrst()
{
LIMITED_METHOD_CONTRACT;
return &m_RefClassFactCrst;
}
#ifndef DACCESS_COMPILE
EEClassFactoryInfoHashTable* GetClassFactHash()
{
STATIC_CONTRACT_THROWS;
STATIC_CONTRACT_GC_TRIGGERS;
STATIC_CONTRACT_FAULT;
if (m_pRefClassFactHash != NULL) {
return m_pRefClassFactHash;
}
return SetupClassFactHash();
}
#endif // DACCESS_COMPILE
#ifdef FEATURE_COMINTEROP
DispIDCache* GetRefDispIDCache()
{
STATIC_CONTRACT_THROWS;
STATIC_CONTRACT_GC_TRIGGERS;
STATIC_CONTRACT_FAULT;
if (m_pRefDispIDCache != NULL) {
return m_pRefDispIDCache;
}
return SetupRefDispIDCache();
}
#endif // FEATURE_COMINTEROP
PTR_LoaderHeap GetStubHeap();
PTR_LoaderHeap GetLowFrequencyHeap();
PTR_LoaderHeap GetHighFrequencyHeap();
virtual PTR_LoaderAllocator GetLoaderAllocator();
#ifdef FEATURE_APPDOMAIN_RESOURCE_MONITORING
#define ARM_ETW_ALLOC_THRESHOLD (4 * 1024 * 1024)
// cache line size in ULONGLONG - 128 bytes which are 16 ULONGLONG's
#define ARM_CACHE_LINE_SIZE_ULL 16
inline ULONGLONG GetAllocBytes()
{
LIMITED_METHOD_CONTRACT;
ULONGLONG ullTotalAllocBytes = 0;
// Ensure that m_pullAllocBytes is non-null to avoid an AV in a race between GC and AD unload.
// A race can occur when a new appdomain is created, but an OOM is thrown when allocating for m_pullAllocBytes, causing the AD unload.
if(NULL != m_pullAllocBytes)
{
for (DWORD i = 0; i < m_dwNumHeaps; i++)
{
ullTotalAllocBytes += m_pullAllocBytes[i * ARM_CACHE_LINE_SIZE_ULL];
}
}
return ullTotalAllocBytes;
}
void RecordAllocBytes(size_t allocatedBytes, DWORD dwHeapNumber)
{
LIMITED_METHOD_CONTRACT;
_ASSERTE(dwHeapNumber < m_dwNumHeaps);
// Ensure that m_pullAllocBytes is non-null to avoid an AV in a race between GC and AD unload.
// A race can occur when a new appdomain is created, but an OOM is thrown when allocating for m_pullAllocBytes, causing the AD unload.
if(NULL != m_pullAllocBytes)
{
m_pullAllocBytes[dwHeapNumber * ARM_CACHE_LINE_SIZE_ULL] += allocatedBytes;
}
ULONGLONG ullTotalAllocBytes = GetAllocBytes();
if ((ullTotalAllocBytes - m_ullLastEtwAllocBytes) >= ARM_ETW_ALLOC_THRESHOLD)
{
m_ullLastEtwAllocBytes = ullTotalAllocBytes;
FireEtwAppDomainMemAllocated((ULONGLONG)this, ullTotalAllocBytes, GetClrInstanceId());
}
}
inline ULONGLONG GetSurvivedBytes()
{
LIMITED_METHOD_CONTRACT;
ULONGLONG ullTotalSurvivedBytes = 0;
// Ensure that m_pullSurvivedBytes is non-null to avoid an AV in a race between GC and AD unload.
// A race can occur when a new appdomain is created, but an OOM is thrown when allocating for m_pullSurvivedBytes, causing the AD unload.
if(NULL != m_pullSurvivedBytes)
{
for (DWORD i = 0; i < m_dwNumHeaps; i++)
{
ullTotalSurvivedBytes += m_pullSurvivedBytes[i * ARM_CACHE_LINE_SIZE_ULL];
}
}
return ullTotalSurvivedBytes;
}
void RecordSurvivedBytes(size_t promotedBytes, DWORD dwHeapNumber)
{
WRAPPER_NO_CONTRACT;
_ASSERTE(dwHeapNumber < m_dwNumHeaps);
// Ensure that m_pullSurvivedBytes is non-null to avoid an AV in a race between GC and AD unload.
// A race can occur when a new appdomain is created, but an OOM is thrown when allocating for m_pullSurvivedBytes, causing the AD unload.
if(NULL != m_pullSurvivedBytes)
{
m_pullSurvivedBytes[dwHeapNumber * ARM_CACHE_LINE_SIZE_ULL] += promotedBytes;
}
}
inline void ResetSurvivedBytes()
{
LIMITED_METHOD_CONTRACT;
// Ensure that m_pullSurvivedBytes is non-null to avoid an AV in a race between GC and AD unload.
// A race can occur when a new appdomain is created, but an OOM is thrown when allocating for m_pullSurvivedBytes, causing the AD unload.
if(NULL != m_pullSurvivedBytes)
{
for (DWORD i = 0; i < m_dwNumHeaps; i++)
{
m_pullSurvivedBytes[i * ARM_CACHE_LINE_SIZE_ULL] = 0;
}
}
}
// Return the total processor time (user and kernel) used by threads executing in this AppDomain so far.
// The result is in 100ns units.
ULONGLONG QueryProcessorUsage();
// Add to the current count of processor time used by threads within this AppDomain. This API is called by
// threads transitioning between AppDomains.
void UpdateProcessorUsage(ULONGLONG ullAdditionalUsage);
#endif //FEATURE_APPDOMAIN_RESOURCE_MONITORING
private:
static void RaiseOneExitProcessEvent_Wrapper(AppDomainIterator* pi);
static void RaiseOneExitProcessEvent();
size_t EstimateSize();
EEClassFactoryInfoHashTable* SetupClassFactHash();
#ifdef FEATURE_COMINTEROP
DispIDCache* SetupRefDispIDCache();
COMorRemotingFlag GetPreferComInsteadOfManagedRemotingFromConfigFile();
#endif // FEATURE_COMINTEROP
void InitializeDefaultDomainManager ();
#ifdef FEATURE_CLICKONCE
void InitializeDefaultClickOnceDomain();
#endif // FEATURE_CLICKONCE
void InitializeDefaultDomainSecurity();
public:
#ifdef FEATURE_CLICKONCE
BOOL IsClickOnceAppDomain();
#endif // FEATURE_CLICKONCE
protected:
BOOL PostBindResolveAssembly(AssemblySpec *pPrePolicySpec,
AssemblySpec *pPostPolicySpec,
HRESULT hrBindResult,
AssemblySpec **ppFailedSpec);
#ifdef FEATURE_COMINTEROP
public:
void ReleaseRCWs(LPVOID pCtxCookie);
void DetachRCWs();
protected:
#endif // FEATURE_COMINTEROP
LPWSTR m_pwDynamicDir;
private:
void RaiseLoadingAssemblyEvent(DomainAssembly* pAssembly);
friend class DomainAssembly;
public:
static void ProcessUnloadDomainEventOnFinalizeThread();
static BOOL HasWorkForFinalizerThread()
{
LIMITED_METHOD_CONTRACT;
return s_pAppDomainToRaiseUnloadEvent != NULL;
}
private:
static AppDomain* s_pAppDomainToRaiseUnloadEvent;
static BOOL s_fProcessUnloadDomainEvent;
void RaiseUnloadDomainEvent();
static void RaiseUnloadDomainEvent_Wrapper(LPVOID /* AppDomain * */);
BOOL RaiseUnhandledExceptionEvent(OBJECTREF *pSender, OBJECTREF *pThrowable, BOOL isTerminating);
BOOL HasUnhandledExceptionEventHandler();
BOOL RaiseUnhandledExceptionEventNoThrow(OBJECTREF *pSender, OBJECTREF *pThrowable, BOOL isTerminating);
struct RaiseUnhandled_Args
{
AppDomain *pExceptionDomain;
AppDomain *pTargetDomain;
OBJECTREF *pSender;
OBJECTREF *pThrowable;
BOOL isTerminating;
BOOL *pResult;
};
#ifndef FEATURE_CORECLR
static void RaiseUnhandledExceptionEvent_Wrapper(LPVOID /* RaiseUnhandled_Args * */);
#endif
static void AllowThreadEntrance(AppDomain *pApp);
static void RestrictThreadEntrance(AppDomain *pApp);
typedef Holder<AppDomain*,DoNothing<AppDomain*>,AppDomain::AllowThreadEntrance,NULL> RestrictEnterHolder;
enum Stage {
STAGE_CREATING,
STAGE_READYFORMANAGEDCODE,
STAGE_ACTIVE,
STAGE_OPEN,
STAGE_UNLOAD_REQUESTED,
STAGE_EXITING,
STAGE_EXITED,
STAGE_FINALIZING,
STAGE_FINALIZED,
STAGE_HANDLETABLE_NOACCESS,
STAGE_CLEARED,
STAGE_COLLECTED,
STAGE_CLOSED
};
void SetStage(Stage stage)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
SO_TOLERANT;
MODE_ANY;
}
CONTRACTL_END;
STRESS_LOG2(LF_APPDOMAIN, LL_INFO100,"Updating AD stage, ADID=%d, stage=%d\n",GetId().m_dwId,stage);
TESTHOOKCALL(AppDomainStageChanged(GetId().m_dwId,m_Stage,stage));
Stage lastStage=m_Stage;
while (lastStage !=stage)
lastStage = (Stage)FastInterlockCompareExchange((LONG*)&m_Stage,stage,lastStage);
};
void Exit(BOOL fRunFinalizers, BOOL fAsyncExit);
void Close();
void ClearGCRoots();
void ClearGCHandles();
void HandleAsyncPinHandles();
void UnwindThreads();
// Return TRUE if EE is stopped
// Return FALSE if more work is needed
BOOL StopEEAndUnwindThreads(unsigned int retryCount, BOOL *pFMarkUnloadRequestThread);
// Use Rude Abort to unload the domain.
BOOL m_fRudeUnload;
Thread *m_pUnloadRequestThread;
ADUnloadSink* m_ADUnloadSink;
BOOL m_bForceGCOnUnload;
BOOL m_bUnloadingFromUnloadEvent;
AppDomainLoaderAllocator m_LoaderAllocator;
// List of unloaded LoaderAllocators, protected by code:GetLoaderAllocatorReferencesLock (for now)
LoaderAllocator * m_pDelayedLoaderAllocatorUnloadList;
public:
// Register the loader allocator for deletion in code:ShutdownFreeLoaderAllocators.
void RegisterLoaderAllocatorForDeletion(LoaderAllocator * pLoaderAllocator);
AppDomain * m_pNextInDelayedUnloadList;
void SetForceGCOnUnload(BOOL bSet)
{
m_bForceGCOnUnload=bSet;
}
void SetUnloadingFromUnloadEvent()
{
m_bUnloadingFromUnloadEvent=TRUE;
}
BOOL IsUnloadingFromUnloadEvent()
{
return m_bUnloadingFromUnloadEvent;
}
void SetRudeUnload()
{
LIMITED_METHOD_CONTRACT;
m_fRudeUnload = TRUE;
}
BOOL IsRudeUnload()
{
LIMITED_METHOD_CONTRACT;
return m_fRudeUnload;
}
ADUnloadSink* GetADUnloadSink();
ADUnloadSink* GetADUnloadSinkForUnload();
void SetUnloadRequestThread(Thread *pThread)
{
LIMITED_METHOD_CONTRACT;
m_pUnloadRequestThread = pThread;
}
Thread *GetUnloadRequestThread()
{
LIMITED_METHOD_CONTRACT;
return m_pUnloadRequestThread;
}
public:
void SetGCRefPoint(int gccounter)
{
LIMITED_METHOD_CONTRACT;
m_LoaderAllocator.SetGCRefPoint(gccounter);
}
int GetGCRefPoint()
{
LIMITED_METHOD_CONTRACT;
return m_LoaderAllocator.GetGCRefPoint();
}
static USHORT GetOffsetOfId()
{
LIMITED_METHOD_CONTRACT;
size_t ofs = offsetof(class AppDomain, m_dwId);
_ASSERTE(FitsInI2(ofs));
return (USHORT)ofs;
}
void AddMemoryPressure();
void RemoveMemoryPressure();
void Unload(BOOL fForceUnload);
static HRESULT UnloadById(ADID Id, BOOL fSync, BOOL fExceptionsPassThrough=FALSE);
static HRESULT UnloadWait(ADID Id, ADUnloadSink* pSink);
#ifdef FEATURE_TESTHOOKS
static HRESULT UnloadWaitNoCatch(ADID Id, ADUnloadSink* pSink);
#endif
static void ResetUnloadRequestThread(ADID Id);
void UnlinkClass(MethodTable *pMT);
typedef Holder<AppDomain *, AppDomain::SetUnloadInProgress, AppDomain::SetUnloadComplete> UnloadHolder;
Assembly *GetRootAssembly()
{
LIMITED_METHOD_CONTRACT;
return m_pRootAssembly;
}
#ifndef DACCESS_COMPILE
void SetRootAssembly(Assembly *pAssembly)
{
LIMITED_METHOD_CONTRACT;
m_pRootAssembly = pAssembly;
}
#endif
private:
SString m_friendlyName;
PTR_Assembly m_pRootAssembly;
// General purpose flags.
DWORD m_dwFlags;
// When an application domain is created the ref count is artifically incremented
// by one. For it to hit zero an explicit close must have happened.
LONG m_cRef; // Ref count.
PTR_IApplicationSecurityDescriptor m_pSecDesc; // Application Security Descriptor
OBJECTHANDLE m_ExposedObject;
#ifdef FEATURE_LOADER_OPTIMIZATION
// Indicates where assemblies will be loaded for
// this domain. By default all assemblies are loaded into the domain.
// There are two additional settings, all
// assemblies can be loaded into the shared domain or assemblies
// that are strong named are loaded into the shared area.
SharePolicy m_SharePolicy;
#endif
IUnknown *m_pComIPForExposedObject;
// Hash table that maps a clsid to a type
PtrHashMap m_clsidHash;
#ifdef FEATURE_COMINTEROP
// Hash table that maps WinRT class names to MethodTables.
PTR_NameToTypeMapTable m_pNameToTypeMap;
UINT m_vNameToTypeMapVersion;
UINT m_nEpoch; // incremented each time m_pNameToTypeMap is enumerated
// Hash table that remembers the last cached WinRT factory object per type per appdomain.
WinRTFactoryCache *m_pWinRTFactoryCache;
// The wrapper cache for this domain - it has its own CCacheLineAllocator on a per domain basis
// to allow the domain to go away and eventually kill the memory when all refs are gone
ComCallWrapperCache *m_pComCallWrapperCache;
// this cache stores the RCWs in this domain
RCWCache *m_pRCWCache;
// this cache stores the RCW -> CCW references in this domain
RCWRefCache *m_pRCWRefCache;
// The method table used for LicenseInteropHelper
MethodTable* m_pLicenseInteropHelperMT;
#endif // FEATURE_COMINTEROP
AssemblySink* m_pAsyncPool; // asynchronous retrival object pool (only one is kept)
// The index of this app domain among existing app domains (starting from 1)
ADIndex m_dwIndex;
// The thread-pool index of this app domain among existing app domains (starting from 1)
TPIndex m_tpIndex;
#ifdef FEATURE_APPDOMAIN_RESOURCE_MONITORING
ULONGLONG* m_pullAllocBytes;
ULONGLONG* m_pullSurvivedBytes;
DWORD m_dwNumHeaps;
ULONGLONG m_ullLastEtwAllocBytes;
// Total processor time (user and kernel) utilized by threads running in this AppDomain so far. May not
// account for threads currently executing in the AppDomain until a call to QueryProcessorUsage() is
// made.
Volatile<ULONGLONG> m_ullTotalProcessorUsage;
#endif //FEATURE_APPDOMAIN_RESOURCE_MONITORING
#ifdef _DEBUG
struct ThreadTrackInfo;
typedef CDynArray<ThreadTrackInfo *> ThreadTrackInfoList;
ThreadTrackInfoList *m_pThreadTrackInfoList;
DWORD m_TrackSpinLock;
#endif
// IL stub cache with fabricated MethodTable parented by a random module in this AD.
ILStubCache m_ILStubCache;
// U->M thunks created in this domain and not associated with a delegate.
// The cache is keyed by MethodDesc pointers.
UMEntryThunkCache *m_pUMEntryThunkCache;
// The number of times we have entered this AD
ULONG m_dwThreadEnterCount;
// The number of threads that have entered this AD, for ADU only
ULONG m_dwThreadsStillInAppDomain;
Volatile<Stage> m_Stage;
// The default context for this domain
Context *m_pDefaultContext;
SString m_applicationBase;
SString m_privateBinPaths;
SString m_configFile;
ArrayList m_failedAssemblies;
DomainAssembly * m_anonymouslyHostedDynamicMethodsAssembly;
#ifdef _DEBUG
Volatile<LONG> m_dwIterHolders;
Volatile<LONG> m_dwRefTakers;
Volatile<LONG> m_dwCreationHolders;
#endif
//
// DAC iterator for failed assembly loads
//
class FailedAssemblyIterator
{
ArrayList::Iterator m_i;
public:
BOOL Next()
{
WRAPPER_NO_CONTRACT;
return m_i.Next();
}
FailedAssembly *GetFailedAssembly()
{
WRAPPER_NO_CONTRACT;
return dac_cast<PTR_FailedAssembly>(m_i.GetElement());
}
SIZE_T GetIndex()
{
WRAPPER_NO_CONTRACT;
return m_i.GetIndex();
}
private:
friend class AppDomain;
// Cannot have constructor so this iterator can be used inside a union
static FailedAssemblyIterator Create(AppDomain *pDomain)
{
WRAPPER_NO_CONTRACT;
FailedAssemblyIterator i;
i.m_i = pDomain->m_failedAssemblies.Iterate();
return i;
}
};
friend class FailedAssemblyIterator;
FailedAssemblyIterator IterateFailedAssembliesEx()
{
WRAPPER_NO_CONTRACT;
return FailedAssemblyIterator::Create(this);
}
//---------------------------------------------------------
// Stub caches for Method stubs
//---------------------------------------------------------
#ifdef FEATURE_FUSION
void TurnOnBindingRedirects();
#endif
public:
#if defined(FEATURE_HOST_ASSEMBLY_RESOLVER)
private:
Volatile<BOOL> m_fIsBindingModelLocked;
public:
BOOL IsHostAssemblyResolverInUse();
BOOL IsBindingModelLocked();
BOOL LockBindingModel();
#endif // defined(FEATURE_HOST_ASSEMBLY_RESOLVER)
UMEntryThunkCache *GetUMEntryThunkCache();
ILStubCache* GetILStubCache()
{
LIMITED_METHOD_CONTRACT;
return &m_ILStubCache;
}
static AppDomain* GetDomain(ILStubCache* pILStubCache)
{
return CONTAINING_RECORD(pILStubCache, AppDomain, m_ILStubCache);
}
enum {
CONTEXT_INITIALIZED = 0x0001,
USER_CREATED_DOMAIN = 0x0002, // created by call to AppDomain.CreateDomain
ALLOCATEDCOM = 0x0008,
LOAD_SYSTEM_ASSEMBLY_EVENT_SENT = 0x0040,
REMOTING_CONFIGURED_FOR_DOMAIN = 0x0100,
COMPILATION_DOMAIN = 0x0400, // Are we ngenning?
APP_DOMAIN_CAN_BE_UNLOADED = 0x0800, // if need extra bits, can derive this at runtime
ORPHANED_LOCKS = 0x1000, // Orphaned locks exist in this appdomain.
PASSIVE_DOMAIN = 0x2000, // Can we execute code in this AppDomain
VERIFICATION_DOMAIN = 0x4000, // This is a verification domain
ILLEGAL_VERIFICATION_DOMAIN = 0x8000, // This can't be a verification domain
IGNORE_UNHANDLED_EXCEPTIONS = 0x10000, // AppDomain was created using the APPDOMAIN_IGNORE_UNHANDLED_EXCEPTIONS flag
ENABLE_PINVOKE_AND_CLASSIC_COMINTEROP = 0x20000, // AppDomain was created using the APPDOMAIN_ENABLE_PINVOKE_AND_CLASSIC_COMINTEROP flag
#ifdef FEATURE_CORECLR
ENABLE_SKIP_PLAT_CHECKS = 0x200000, // Skip various assembly checks (like platform check)
ENABLE_ASSEMBLY_LOADFILE = 0x400000, // Allow Assembly.LoadFile in CoreCLR
DISABLE_TRANSPARENCY_ENFORCEMENT= 0x800000, // Disable enforcement of security transparency rules
#endif
};
SecurityContext *m_pSecContext;
AssemblySpecBindingCache m_AssemblyCache;
DomainAssemblyCache m_UnmanagedCache;
size_t m_MemoryPressure;
SString m_AppDomainManagerAssembly;
SString m_AppDomainManagerType;
BOOL m_fAppDomainManagerSetInConfig;
EInitializeNewDomainFlags m_dwAppDomainManagerInitializeDomainFlags;
#ifdef FEATURE_CORECLR
ArrayList m_NativeDllSearchDirectories;
#endif
BOOL m_ReversePInvokeCanEnter;
bool m_ForceTrivialWaitOperations;
// Section to support AD unload due to escalation
public:
static void CreateADUnloadWorker();
static void CreateADUnloadStartEvent();
static DWORD WINAPI ADUnloadThreadStart(void *args);
// Default is safe unload with test hook
void EnableADUnloadWorker();
// If called to handle stack overflow, we can not set event, since the thread has limit stack.
void EnableADUnloadWorker(EEPolicy::AppDomainUnloadTypes type, BOOL fHasStack = TRUE);
static void EnableADUnloadWorkerForThreadAbort();
static void EnableADUnloadWorkerForFinalizer();
static void EnableADUnloadWorkerForCollectedADCleanup();
BOOL IsUnloadRequested()
{
LIMITED_METHOD_CONTRACT;
return (m_Stage == STAGE_UNLOAD_REQUESTED);
}
#ifdef FEATURE_CORECLR
BOOL IsImageFromTrustedPath(PEImage* pImage);
BOOL IsImageFullyTrusted(PEImage* pImage);
#endif
#ifdef FEATURE_TYPEEQUIVALENCE
private:
VolatilePtr<TypeEquivalenceHashTable> m_pTypeEquivalenceTable;
CrstExplicitInit m_TypeEquivalenceCrst;
public:
TypeEquivalenceHashTable * GetTypeEquivalenceCache();
#endif
private:
static void ADUnloadWorkerHelper(AppDomain *pDomain);
static CLREvent * g_pUnloadStartEvent;
#ifdef DACCESS_COMPILE
public:
virtual void EnumMemoryRegions(CLRDataEnumMemoryFlags flags,
bool enumThis);
#endif
#ifdef FEATURE_MULTICOREJIT
private:
MulticoreJitManager m_MulticoreJitManager;
public:
MulticoreJitManager & GetMulticoreJitManager()
{
LIMITED_METHOD_CONTRACT;
return m_MulticoreJitManager;
}
#endif
#ifdef FEATURE_COMINTEROP
private:
#ifdef FEATURE_REFLECTION_ONLY_LOAD
// ReflectionOnly WinRT binder and its TypeCache (only in classic = non-AppX; the scenario is not supported in AppX)
CLRPrivBinderReflectionOnlyWinRT * m_pReflectionOnlyWinRtBinder;
CLRPrivTypeCacheReflectionOnlyWinRT * m_pReflectionOnlyWinRtTypeCache;
#endif // FEATURE_REFLECTION_ONLY_LOAD
#endif //FEATURE_COMINTEROP
public:
#ifndef FEATURE_CORECLR
BOOL m_bUseOsSorting;
DWORD m_sortVersion;
COMNlsCustomSortLibrary *m_pCustomSortLibrary;
#if _DEBUG
BOOL m_bSortingInitialized;
#endif // _DEBUG
COMNlsHashProvider *m_pNlsHashProvider;
#endif // !FEATURE_CORECLR
#ifdef FEATURE_HOSTED_BINDER
private:
// This is the root-level default load context root binder. If null, then
// the Fusion binder is used; otherwise this binder is used.
ReleaseHolder<ICLRPrivBinder> m_pLoadContextHostBinder;
// -------------------------
// IMPORTANT!
// The shared and designer context binders are ONLY to be used in tool
// scenarios. There are known issues where use of these binders will
// cause application crashes, and interesting behaviors.
// -------------------------
// This is the default designer shared context root binder.
// This is used as the parent binder for ImmersiveDesignerContextBinders
ReleaseHolder<ICLRPrivBinder> m_pSharedContextHostBinder;
// This is the current context root binder.
// Normally, this variable is immutable for appdomain lifetime, but in designer scenarios
// it may be replaced by designer context binders
Volatile<ICLRPrivBinder *> m_pCurrentContextHostBinder;
public:
// Returns the current hosted binder, or null if none available.
inline
ICLRPrivBinder * GetCurrentLoadContextHostBinder() const
{
LIMITED_METHOD_CONTRACT;
return m_pCurrentContextHostBinder;
}
// Returns the shared context binder, or null if none available.
inline
ICLRPrivBinder * GetSharedContextHostBinder() const
{
LIMITED_METHOD_CONTRACT;
return m_pSharedContextHostBinder;
}
// Returns the load context binder, or null if none available.
inline
ICLRPrivBinder * GetLoadContextHostBinder() const
{
LIMITED_METHOD_CONTRACT;
return m_pLoadContextHostBinder;
}
#ifndef DACCESS_COMPILE
// This is only called from the ImmersiveDesignerContext code
// It is protected with a managed monitor lock
inline
void SetSharedContextHostBinder(ICLRPrivBinder * pBinder)
{
LIMITED_METHOD_CONTRACT;
pBinder->AddRef();
m_pSharedContextHostBinder = pBinder;
}
// This is called from CorHost2's implementation of ICLRPrivRuntime::CreateAppDomain.
// Should only be called during AppDomain creation.
inline
void SetLoadContextHostBinder(ICLRPrivBinder * pBinder)
{
LIMITED_METHOD_CONTRACT;
pBinder->AddRef();
m_pLoadContextHostBinder = m_pCurrentContextHostBinder = pBinder;
}
inline
void SetCurrentContextHostBinder(ICLRPrivBinder * pBinder)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
}
CONTRACTL_END;
LockHolder lh(this);
#ifdef FEATURE_COMINTEROP
if (m_pNameToTypeMap != nullptr)
{
delete m_pNameToTypeMap;
m_pNameToTypeMap = nullptr;
}
m_vNameToTypeMapVersion++;
#endif
m_pCurrentContextHostBinder = pBinder;
}
#endif // DACCESS_COMPILE
// Indicates that a hosted binder is present.
inline
bool HasLoadContextHostBinder()
{
LIMITED_METHOD_CONTRACT;
return m_pLoadContextHostBinder != nullptr;
}
class ComInterfaceReleaseList
{
SArray<IUnknown *> m_objects;
public:
~ComInterfaceReleaseList()
{
WRAPPER_NO_CONTRACT;
for (COUNT_T i = 0; i < m_objects.GetCount(); i++)
{
IUnknown *pItf = *(m_objects.GetElements() + i);
if (pItf != nullptr)
pItf->Release();
}
}
// Append to the list of object to free. Only use under the AppDomain "LockHolder(pAppDomain)"
void Append(IUnknown *pInterfaceToRelease)
{
WRAPPER_NO_CONTRACT;
m_objects.Append(pInterfaceToRelease);
}
} AppDomainInterfaceReleaseList;
private:
//-----------------------------------------------------------
// Static ICLRPrivAssembly -> DomainAssembly mapping functions.
// This map does not maintain a reference count to either key or value.
// PEFile maintains a reference count on the ICLRPrivAssembly through its code:PEFile::m_pHostAssembly field.
// It is removed from this hash table by code:DomainAssembly::~DomainAssembly.
struct HostAssemblyHashTraits : public DefaultSHashTraits<PTR_DomainAssembly>
{
public:
typedef PTR_ICLRPrivAssembly key_t;
static key_t GetKey(element_t const & elem)
{
STATIC_CONTRACT_WRAPPER;
return elem->GetFile()->GetHostAssembly();
}
static BOOL Equals(key_t key1, key_t key2)
{
LIMITED_METHOD_CONTRACT;
return dac_cast<TADDR>(key1) == dac_cast<TADDR>(key2);
}
static count_t Hash(key_t key)
{
STATIC_CONTRACT_LIMITED_METHOD;
//return reinterpret_cast<count_t>(dac_cast<TADDR>(key));
return (count_t)(dac_cast<TADDR>(key));
}
static const element_t Null() { return NULL; }
static const element_t Deleted() { return (element_t)(TADDR)-1; }
static bool IsNull(const element_t & e) { return e == NULL; }
static bool IsDeleted(const element_t & e) { return dac_cast<TADDR>(e) == (TADDR)-1; }
};
struct OriginalFileHostAssemblyHashTraits : public HostAssemblyHashTraits
{
public:
static key_t GetKey(element_t const & elem)
{
STATIC_CONTRACT_WRAPPER;
return elem->GetOriginalFile()->GetHostAssembly();
}
};
typedef SHash<HostAssemblyHashTraits> HostAssemblyMap;
typedef SHash<OriginalFileHostAssemblyHashTraits> OriginalFileHostAssemblyMap;
HostAssemblyMap m_hostAssemblyMap;
OriginalFileHostAssemblyMap m_hostAssemblyMapForOrigFile;
CrstExplicitInit m_crstHostAssemblyMap;
// Lock to serialize all Add operations (in addition to the "read-lock" above)
CrstExplicitInit m_crstHostAssemblyMapAdd;
public:
// Returns DomainAssembly.
PTR_DomainAssembly FindAssembly(PTR_ICLRPrivAssembly pHostAssembly);
#ifndef DACCESS_COMPILE
private:
friend void DomainAssembly::Allocate();
friend DomainAssembly::~DomainAssembly();
// Called from DomainAssembly::Begin.
void PublishHostedAssembly(
DomainAssembly* pAssembly);
// Called from DomainAssembly::UpdatePEFile.
void UpdatePublishHostedAssembly(
DomainAssembly* pAssembly,
PTR_PEFile pFile);
// Called from DomainAssembly::~DomainAssembly
void UnPublishHostedAssembly(
DomainAssembly* pAssembly);
#endif // DACCESS_COMPILE
#endif //FEATURE_HOSTED_BINDER
#ifdef FEATURE_PREJIT
friend void DomainFile::InsertIntoDomainFileWithNativeImageList();
Volatile<DomainFile *> m_pDomainFileWithNativeImageList;
public:
DomainFile *GetDomainFilesWithNativeImagesList()
{
LIMITED_METHOD_CONTRACT;
return m_pDomainFileWithNativeImageList;
}
#endif
}; // class AppDomain
// This holder is to be used to take a reference to make sure AppDomain* is still valid
// Please do not use if you are aleady ADU-safe
typedef Wrapper<AppDomain*,AppDomain::RefTakerAcquire,AppDomain::RefTakerRelease,NULL> AppDomainRefTaker;
// Just a ref holder
typedef ReleaseHolder<AppDomain> AppDomainRefHolder;
// This class provides a way to access AppDomain by ID
// without risking the appdomain getting invalid in the process
class AppDomainFromIDHolder
{
public:
enum SyncType
{
SyncType_GC, // Prevents AD from being unloaded by forbidding GC for the lifetime of the object
SyncType_ADLock // Prevents AD from being unloaded by requiring ownership of DomainLock for the lifetime of the object
};
protected:
AppDomain* m_pDomain;
#ifdef _DEBUG
BOOL m_bAcquired;
BOOL m_bChecked;
SyncType m_type;
#endif
public:
DEBUG_NOINLINE AppDomainFromIDHolder(ADID adId, BOOL bUnsafePoint, SyncType synctype=SyncType_GC);
DEBUG_NOINLINE AppDomainFromIDHolder(SyncType synctype=SyncType_GC);
DEBUG_NOINLINE ~AppDomainFromIDHolder();
void* GetAddress() { return m_pDomain; } // Used to get an identfier for ETW
void Assign(ADID adId, BOOL bUnsafePoint);
void ThrowIfUnloaded();
void Release();
BOOL IsUnloaded()
{
LIMITED_METHOD_CONTRACT;
#ifdef _DEBUG
m_bChecked=TRUE;
if (m_pDomain==NULL)
{
// no need to enforce anything
Release();
}
#endif
return m_pDomain==NULL;
};
AppDomain* operator->();
}; // class AppDomainFromIDHolder
typedef VPTR(class SystemDomain) PTR_SystemDomain;
class SystemDomain : public BaseDomain
{
friend class AppDomainNative;
friend class AppDomainIterator;
friend class UnsafeAppDomainIterator;
friend class ClrDataAccess;
friend class AppDomainFromIDHolder;
friend Frame *Thread::IsRunningIn(AppDomain* pDomain, int *count);
VPTR_VTABLE_CLASS(SystemDomain, BaseDomain)
VPTR_UNIQUE(VPTR_UNIQUE_SystemDomain)
static AppDomain *GetAppDomainAtId(ADID indx);
public:
static PTR_LoaderAllocator GetGlobalLoaderAllocator();
virtual PTR_LoaderAllocator GetLoaderAllocator() { WRAPPER_NO_CONTRACT; return GetGlobalLoaderAllocator(); }
static AppDomain* GetAppDomainFromId(ADID indx,DWORD ADValidityKind)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_COOPERATIVE;
}
CONTRACTL_END;
AppDomain* pRetVal;
if (indx.m_dwId==DefaultADID)
pRetVal= SystemDomain::System()->DefaultDomain();
else
pRetVal= GetAppDomainAtId(indx);
#ifdef _DEBUG
// Only call CheckADValidity in DEBUG builds for non-NULL return values
if (pRetVal != NULL)
CheckADValidity(pRetVal, ADValidityKind);
#endif
return pRetVal;
}
//****************************************************************************************
//
// To be run during the initial start up of the EE. This must be
// performed prior to any class operations.
static void Attach();
//****************************************************************************************
//
// To be run during shutdown. This must be done after all operations
// that require the use of system classes (i.e., exceptions).
// DetachBegin stops all domains, while DetachEnd deallocates domain resources.
static void DetachBegin();
//****************************************************************************************
//
// To be run during shutdown. This must be done after all operations
// that require the use of system classes (i.e., exceptions).
// DetachBegin stops release resources held by systemdomain and the default domain.
static void DetachEnd();
//****************************************************************************************
//
// Initializes and shutdowns the single instance of the SystemDomain
// in the EE
#ifndef DACCESS_COMPILE
void *operator new(size_t size, void *pInPlace);
void operator delete(void *pMem);
#endif
void Init();
void Stop();
void Terminate();
static void LazyInitGlobalStringLiteralMap();
//****************************************************************************************
//
// Load the base system classes, these classes are required before
// any other classes are loaded
void LoadBaseSystemClasses();
AppDomain* DefaultDomain()
{
LIMITED_METHOD_DAC_CONTRACT;
return m_pDefaultDomain;
}
// Notification when an assembly is loaded into the system domain
void OnAssemblyLoad(Assembly *assem);
//****************************************************************************************
//
// Global Static to get the one and only system domain
static SystemDomain * System()
{
LIMITED_METHOD_DAC_CONTRACT;
return m_pSystemDomain;
}
static PEAssembly* SystemFile()
{
WRAPPER_NO_CONTRACT;
_ASSERTE(m_pSystemDomain);
return System()->m_pSystemFile;
}
static Assembly* SystemAssembly()
{
WRAPPER_NO_CONTRACT;
return System()->m_pSystemAssembly;
}
static Module* SystemModule()
{
WRAPPER_NO_CONTRACT;
return SystemAssembly()->GetManifestModule();
}
static BOOL IsSystemLoaded()
{
WRAPPER_NO_CONTRACT;
return System()->m_pSystemAssembly != NULL;
}
#ifndef DACCESS_COMPILE
static GlobalStringLiteralMap *GetGlobalStringLiteralMap()
{
WRAPPER_NO_CONTRACT;
if (m_pGlobalStringLiteralMap == NULL)
{
SystemDomain::LazyInitGlobalStringLiteralMap();
}
_ASSERTE(m_pGlobalStringLiteralMap);
return m_pGlobalStringLiteralMap;
}
static GlobalStringLiteralMap *GetGlobalStringLiteralMapNoCreate()
{
LIMITED_METHOD_CONTRACT;
_ASSERTE(m_pGlobalStringLiteralMap);
return m_pGlobalStringLiteralMap;
}
#endif // DACCESS_COMPILE
#ifndef FEATURE_CORECLR
static void ExecuteMainMethod(HMODULE hMod, __in_opt LPWSTR path = NULL);
#endif
static void ActivateApplication(int *pReturnValue);
static void InitializeDefaultDomain(
BOOL allowRedirects
#ifdef FEATURE_HOSTED_BINDER
, ICLRPrivBinder * pBinder = NULL
#endif
);
static void SetupDefaultDomain();
static HRESULT SetupDefaultDomainNoThrow();
#if defined(FEATURE_COMINTEROP_APARTMENT_SUPPORT) && !defined(CROSSGEN_COMPILE)
static Thread::ApartmentState GetEntryPointThreadAptState(IMDInternalImport* pScope, mdMethodDef mdMethod);
static void SetThreadAptState(IMDInternalImport* pScope, Thread::ApartmentState state);
#endif
static BOOL SetGlobalSharePolicyUsingAttribute(IMDInternalImport* pScope, mdMethodDef mdMethod);
#ifdef FEATURE_MIXEDMODE
static HRESULT RunDllMain(HINSTANCE hInst, DWORD dwReason, LPVOID lpReserved);
#endif // FEATURE_MIXEDMODE
//****************************************************************************************
//
// Use an already exising & inited Application Domain (e.g. a subclass).
static void LoadDomain(AppDomain *pDomain);
#ifndef DACCESS_COMPILE
static void MakeUnloadable(AppDomain* pApp)
{
WRAPPER_NO_CONTRACT;
System()->AddDomain(pApp);
pApp->SetCanUnload();
}
#endif // DACCESS_COMPILE
//****************************************************************************************
// Methods used to get the callers module and hence assembly and app domain.
__declspec(deprecated("This method is deprecated, use the version that takes a StackCrawlMark instead"))
static Module* GetCallersModule(int skip);
static MethodDesc* GetCallersMethod(StackCrawlMark* stackMark, AppDomain **ppAppDomain = NULL);
static MethodTable* GetCallersType(StackCrawlMark* stackMark, AppDomain **ppAppDomain = NULL);
static Module* GetCallersModule(StackCrawlMark* stackMark, AppDomain **ppAppDomain = NULL);
static Assembly* GetCallersAssembly(StackCrawlMark* stackMark, AppDomain **ppAppDomain = NULL);
static bool IsReflectionInvocationMethod(MethodDesc* pMeth);
#ifndef DACCESS_COMPILE
//****************************************************************************************
// Returns the domain associated with the current context. (this can only be a child domain)
static inline AppDomain * GetCurrentDomain()
{
WRAPPER_NO_CONTRACT;
return ::GetAppDomain();
}
#endif //!DACCESS_COMPILE
#ifdef DEBUGGING_SUPPORTED
//****************************************************************************************
// Debugger/Publisher helper function to indicate creation of new app domain to debugger
// and publishing it in the IPC block
static void PublishAppDomainAndInformDebugger (AppDomain *pDomain);
#endif // DEBUGGING_SUPPORTED
//****************************************************************************************
// Helper function to remove a domain from the system
BOOL RemoveDomain(AppDomain* pDomain); // Does not decrement the reference
#ifdef PROFILING_SUPPORTED
//****************************************************************************************
// Tell profiler about system created domains which are created before the profiler is
// actually activated.
static void NotifyProfilerStartup();
//****************************************************************************************
// Tell profiler at shutdown that system created domains are going away. They are not
// torn down using the normal sequence.
static HRESULT NotifyProfilerShutdown();
#endif // PROFILING_SUPPORTED
//****************************************************************************************
// return the dev path
#ifdef FEATURE_FUSION
void GetDevpathW(__out_ecount_opt(1) LPWSTR* pPath, DWORD* pSize);
#endif
#ifndef DACCESS_COMPILE
void IncrementNumAppDomains ()
{
LIMITED_METHOD_CONTRACT;
s_dNumAppDomains++;
}
void DecrementNumAppDomains ()
{
LIMITED_METHOD_CONTRACT;
s_dNumAppDomains--;
}
ULONG GetNumAppDomains ()
{
LIMITED_METHOD_CONTRACT;
return s_dNumAppDomains;
}
#endif // DACCESS_COMPILE
//
// AppDomains currently have both an index and an ID. The
// index is "densely" assigned; indices are reused as domains
// are unloaded. The Id's on the other hand, are not reclaimed
// so may be sparse.
//
// Another important difference - it's OK to call GetAppDomainAtId for
// an unloaded domain (it will return NULL), while GetAppDomainAtIndex
// will assert if the domain is unloaded.
//<TODO>
// @todo:
// I'm not really happy with this situation, but
// (a) we need an ID for a domain which will last the process lifetime for the
// remoting code.
// (b) we need a dense ID, for the handle table index.
// So for now, I'm leaving both, but hopefully in the future we can come up
// with something better.
//</TODO>
static ADIndex GetNewAppDomainIndex(AppDomain * pAppDomain);
static void ReleaseAppDomainIndex(ADIndex indx);
static PTR_AppDomain GetAppDomainAtIndex(ADIndex indx);
static PTR_AppDomain TestGetAppDomainAtIndex(ADIndex indx);
static DWORD GetCurrentAppDomainMaxIndex()
{
WRAPPER_NO_CONTRACT;
ArrayListStatic* list = (ArrayListStatic *)&m_appDomainIndexList;
PREFIX_ASSUME(list!=NULL);
return list->GetCount();
}
static ADID GetNewAppDomainId(AppDomain *pAppDomain);
static void ReleaseAppDomainId(ADID indx);
#ifndef DACCESS_COMPILE
static ADID GetCurrentAppDomainMaxId() { ADID id; id.m_dwId=m_appDomainIdList.GetCount(); return id;}
#endif // DACCESS_COMPILE
#ifndef DACCESS_COMPILE
DWORD RequireAppDomainCleanup()
{
LIMITED_METHOD_CONTRACT;
return m_pDelayedUnloadList != 0 || m_pDelayedUnloadListOfLoaderAllocators != 0;
}
void AddToDelayedUnloadList(AppDomain* pDomain, BOOL bAsync)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_COOPERATIVE;
}
CONTRACTL_END;
m_UnloadIsAsync = bAsync;
CrstHolder lh(&m_DelayedUnloadCrst);
pDomain->m_pNextInDelayedUnloadList=m_pDelayedUnloadList;
m_pDelayedUnloadList=pDomain;
if (m_UnloadIsAsync)
{
pDomain->AddRef();
int iGCRefPoint=GCHeap::GetGCHeap()->CollectionCount(GCHeap::GetGCHeap()->GetMaxGeneration());
if (GCHeap::GetGCHeap()->IsGCInProgress())
iGCRefPoint++;
pDomain->SetGCRefPoint(iGCRefPoint);
}
}
void AddToDelayedUnloadList(LoaderAllocator * pAllocator)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_COOPERATIVE;
}
CONTRACTL_END;
CrstHolder lh(&m_DelayedUnloadCrst);
pAllocator->m_pLoaderAllocatorDestroyNext=m_pDelayedUnloadListOfLoaderAllocators;
m_pDelayedUnloadListOfLoaderAllocators=pAllocator;
int iGCRefPoint=GCHeap::GetGCHeap()->CollectionCount(GCHeap::GetGCHeap()->GetMaxGeneration());
if (GCHeap::GetGCHeap()->IsGCInProgress())
iGCRefPoint++;
pAllocator->SetGCRefPoint(iGCRefPoint);
}
void ClearCollectedDomains();
void ProcessClearingDomains();
void ProcessDelayedUnloadDomains();
static void SetUnloadInProgress(AppDomain *pDomain)
{
WRAPPER_NO_CONTRACT;
_ASSERTE(m_pAppDomainBeingUnloaded == NULL);
m_pAppDomainBeingUnloaded = pDomain;
m_dwIndexOfAppDomainBeingUnloaded = pDomain->GetIndex();
}
static void SetUnloadDomainCleared()
{
LIMITED_METHOD_CONTRACT;
// about to delete, so clear this pointer so nobody uses it
m_pAppDomainBeingUnloaded = NULL;
}
static void SetUnloadComplete()
{
LIMITED_METHOD_CONTRACT;
// should have already cleared the AppDomain* prior to delete
// either we succesfully unloaded and cleared or we failed and restored the ID
_ASSERTE(m_pAppDomainBeingUnloaded == NULL && m_dwIndexOfAppDomainBeingUnloaded.m_dwIndex != 0
|| m_pAppDomainBeingUnloaded && SystemDomain::GetAppDomainAtId(m_pAppDomainBeingUnloaded->GetId()) != NULL);
m_pAppDomainBeingUnloaded = NULL;
m_pAppDomainUnloadingThread = NULL;
}
static AppDomain *AppDomainBeingUnloaded()
{
LIMITED_METHOD_CONTRACT;
return m_pAppDomainBeingUnloaded;
}
static ADIndex IndexOfAppDomainBeingUnloaded()
{
LIMITED_METHOD_CONTRACT;
return m_dwIndexOfAppDomainBeingUnloaded;
}
static void SetUnloadRequestingThread(Thread *pRequestingThread)
{
LIMITED_METHOD_CONTRACT;
m_pAppDomainUnloadRequestingThread = pRequestingThread;
}
static Thread *GetUnloadRequestingThread()
{
LIMITED_METHOD_CONTRACT;
return m_pAppDomainUnloadRequestingThread;
}
static void SetUnloadingThread(Thread *pUnloadingThread)
{
LIMITED_METHOD_CONTRACT;
m_pAppDomainUnloadingThread = pUnloadingThread;
}
static Thread *GetUnloadingThread()
{
LIMITED_METHOD_CONTRACT;
return m_pAppDomainUnloadingThread;
}
static void EnumAllStaticGCRefs(promote_func* fn, ScanContext* sc);
#endif // DACCESS_COMPILE
#ifdef FEATURE_APPDOMAIN_RESOURCE_MONITORING
// The *AD* methods are what we got from tracing through EE roots.
// RecordTotalSurvivedBytes is the total promoted from a GC.
static void ResetADSurvivedBytes();
static ULONGLONG GetADSurvivedBytes();
static void RecordTotalSurvivedBytes(size_t totalSurvivedBytes);
static ULONGLONG GetTotalSurvivedBytes()
{
LIMITED_METHOD_CONTRACT;
return m_totalSurvivedBytes;
}
#endif //FEATURE_APPDOMAIN_RESOURCE_MONITORING
//****************************************************************************************
// Routines to deal with the base library (currently mscorlib.dll)
LPCWSTR BaseLibrary()
{
WRAPPER_NO_CONTRACT;
return m_BaseLibrary;
}
#ifndef DACCESS_COMPILE
BOOL IsBaseLibrary(SString &path)
{
WRAPPER_NO_CONTRACT;
// See if it is the installation path to mscorlib
if (path.EqualsCaseInsensitive(m_BaseLibrary, PEImage::GetFileSystemLocale()))
return TRUE;
// Or, it might be the GAC location of mscorlib
if (System()->SystemAssembly() != NULL
&& path.EqualsCaseInsensitive(System()->SystemAssembly()->GetManifestFile()->GetPath(),
PEImage::GetFileSystemLocale()))
return TRUE;
return FALSE;
}
BOOL IsBaseLibrarySatellite(SString &path)
{
WRAPPER_NO_CONTRACT;
// See if it is the installation path to mscorlib.resources
SString s(SString::Ascii,g_psBaseLibrarySatelliteAssemblyName);
if (path.EqualsCaseInsensitive(s, PEImage::GetFileSystemLocale()))
return TRUE;
// workaround! Must implement some code to do this string comparison for
// mscorlib.resources in a culture-specific directory in the GAC.
/*
// Or, it might be the GAC location of mscorlib.resources
if (System()->SystemAssembly() != NULL
&& path.EqualsCaseInsensitive(System()->SystemAssembly()->GetManifestFile()->GetPath(),
PEImage::GetFileSystemLocale()))
return TRUE;
*/
return FALSE;
}
#endif // DACCESS_COMPILE
// Return the system directory
LPCWSTR SystemDirectory()
{
WRAPPER_NO_CONTRACT;
return m_SystemDirectory;
}
private:
//****************************************************************************************
// Helper function to create the single COM domain
void CreateDefaultDomain();
//****************************************************************************************
// Helper function to add a domain to the global list
void AddDomain(AppDomain* pDomain);
void CreatePreallocatedExceptions();
void PreallocateSpecialObjects();
//****************************************************************************************
//
static StackWalkAction CallersMethodCallback(CrawlFrame* pCrawlFrame, VOID* pClientData);
static StackWalkAction CallersMethodCallbackWithStackMark(CrawlFrame* pCrawlFrame, VOID* pClientData);
#ifndef DACCESS_COMPILE
// This class is not to be created through normal allocation.
SystemDomain()
{
STANDARD_VM_CONTRACT;
m_pDefaultDomain = NULL;
m_pDelayedUnloadList=NULL;
m_pDelayedUnloadListOfLoaderAllocators=NULL;
m_UnloadIsAsync = FALSE;
m_GlobalAllocator.Init(this);
}
#endif
PTR_PEAssembly m_pSystemFile; // Single assembly (here for quicker reference);
PTR_Assembly m_pSystemAssembly; // Single assembly (here for quicker reference);
PTR_AppDomain m_pDefaultDomain; // Default domain for COM+ classes exposed through IClassFactory.
GlobalLoaderAllocator m_GlobalAllocator;
InlineSString<100> m_BaseLibrary;
#ifdef FEATURE_VERSIONING
InlineSString<100> m_SystemDirectory;
#else
LPCWSTR m_SystemDirectory;
#endif
LPWSTR m_pwDevpath;
DWORD m_dwDevpath;
BOOL m_fDevpath; // have we searched the environment
// <TODO>@TODO: CTS, we can keep the com modules in a single assembly or in different assemblies.
// We are currently using different assemblies but this is potentitially to slow...</TODO>
// Global domain that every one uses
SPTR_DECL(SystemDomain, m_pSystemDomain);
AppDomain* m_pDelayedUnloadList;
BOOL m_UnloadIsAsync;
LoaderAllocator * m_pDelayedUnloadListOfLoaderAllocators;
#ifdef FEATURE_APPDOMAIN_RESOURCE_MONITORING
// This is what gets promoted for the whole GC heap.
static size_t m_totalSurvivedBytes;
#endif //FEATURE_APPDOMAIN_RESOURCE_MONITORING
SVAL_DECL(ArrayListStatic, m_appDomainIndexList);
#ifndef DACCESS_COMPILE
static CrstStatic m_DelayedUnloadCrst;
static CrstStatic m_SystemDomainCrst;
static ArrayListStatic m_appDomainIdList;
// only one ad can be unloaded at a time
static AppDomain* m_pAppDomainBeingUnloaded;
// need this so can determine AD being unloaded after it has been deleted
static ADIndex m_dwIndexOfAppDomainBeingUnloaded;
// if had to spin off a separate thread to do the unload, this is the original thread.
// allows us to delay aborting it until it's the last one so that it can receive
// notification of an unload failure
static Thread *m_pAppDomainUnloadRequestingThread;
// this is the thread doing the actual unload. He's allowed to enter the domain
// even if have started unloading.
static Thread *m_pAppDomainUnloadingThread;
static GlobalStringLiteralMap *m_pGlobalStringLiteralMap;
static ULONG s_dNumAppDomains; // Maintain a count of children app domains.
static DWORD m_dwLowestFreeIndex;
#endif // DACCESS_COMPILE
protected:
// These flags let the correct native image of mscorlib to be loaded.
// This is important for hardbinding to it
SVAL_DECL(BOOL, s_fForceDebug);
SVAL_DECL(BOOL, s_fForceProfiling);
SVAL_DECL(BOOL, s_fForceInstrument);
public:
static void SetCompilationOverrides(BOOL fForceDebug,
BOOL fForceProfiling,
BOOL fForceInstrument);
static void GetCompilationOverrides(BOOL * fForceDebug,
BOOL * fForceProfiling,
BOOL * fForceInstrument);
public:
//****************************************************************************************
//
#ifndef DACCESS_COMPILE
#ifdef _DEBUG
inline static BOOL IsUnderDomainLock() { LIMITED_METHOD_CONTRACT; return m_SystemDomainCrst.OwnedByCurrentThread();};
#endif
// This lock controls adding and removing domains from the system domain
class LockHolder : public CrstHolder
{
public:
LockHolder()
: CrstHolder(&m_SystemDomainCrst)
{
WRAPPER_NO_CONTRACT;
}
};
#endif // DACCESS_COMPILE
public:
DWORD GetTotalNumSizedRefHandles();
#ifdef DACCESS_COMPILE
public:
virtual void EnumMemoryRegions(CLRDataEnumMemoryFlags flags,
bool enumThis);
#endif
}; // class SystemDomain
//
// an UnsafeAppDomainIterator is used to iterate over all existing domains
//
// The iteration is guaranteed to include all domains that exist at the
// start & end of the iteration. This iterator is considered unsafe because it does not
// reference count the various appdomains, and can only be used when the runtime is stopped,
// or external synchronization is used. (and therefore no other thread may cause the appdomain list to change.)
//
class UnsafeAppDomainIterator
{
friend class SystemDomain;
public:
UnsafeAppDomainIterator(BOOL bOnlyActive)
{
m_bOnlyActive = bOnlyActive;
}
void Init()
{
LIMITED_METHOD_CONTRACT;
SystemDomain* sysDomain = SystemDomain::System();
if (sysDomain)
{
ArrayListStatic* list = &sysDomain->m_appDomainIndexList;
PREFIX_ASSUME(list != NULL);
m_i = list->Iterate();
}
else
{
m_i.SetEmpty();
}
m_pCurrent = NULL;
}
BOOL Next()
{
WRAPPER_NO_CONTRACT;
while (m_i.Next())
{
m_pCurrent = dac_cast<PTR_AppDomain>(m_i.GetElement());
if (m_pCurrent != NULL &&
(m_bOnlyActive ?
m_pCurrent->IsActive() : m_pCurrent->IsValid()))
{
return TRUE;
}
}
m_pCurrent = NULL;
return FALSE;
}
AppDomain * GetDomain()
{
LIMITED_METHOD_DAC_CONTRACT;
return m_pCurrent;
}
private:
ArrayList::Iterator m_i;
AppDomain * m_pCurrent;
BOOL m_bOnlyActive;
}; // class UnsafeAppDomainIterator
//
// an AppDomainIterator is used to iterate over all existing domains.
//
// The iteration is guaranteed to include all domains that exist at the
// start & end of the iteration. Any domains added or deleted during
// iteration may or may not be included. The iterator also guarantees
// that the current iterated appdomain (GetDomain()) will not be deleted.
//
class AppDomainIterator : public UnsafeAppDomainIterator
{
friend class SystemDomain;
public:
AppDomainIterator(BOOL bOnlyActive) : UnsafeAppDomainIterator(bOnlyActive)
{
WRAPPER_NO_CONTRACT;
Init();
}
~AppDomainIterator()
{
WRAPPER_NO_CONTRACT;
#ifndef DACCESS_COMPILE
if (GetDomain() != NULL)
{
#ifdef _DEBUG
GetDomain()->IteratorRelease();
#endif
GetDomain()->Release();
}
#endif
}
BOOL Next()
{
WRAPPER_NO_CONTRACT;
#ifndef DACCESS_COMPILE
if (GetDomain() != NULL)
{
#ifdef _DEBUG
GetDomain()->IteratorRelease();
#endif
GetDomain()->Release();
}
SystemDomain::LockHolder lh;
#endif
if (UnsafeAppDomainIterator::Next())
{
#ifndef DACCESS_COMPILE
GetDomain()->AddRef();
#ifdef _DEBUG
GetDomain()->IteratorAcquire();
#endif
#endif
return TRUE;
}
return FALSE;
}
}; // class AppDomainIterator
typedef VPTR(class SharedDomain) PTR_SharedDomain;
class SharedDomain : public BaseDomain
{
VPTR_VTABLE_CLASS_AND_CTOR(SharedDomain, BaseDomain)
public:
static void Attach();
static void Detach();
virtual BOOL IsSharedDomain() { LIMITED_METHOD_DAC_CONTRACT; return TRUE; }
virtual PTR_LoaderAllocator GetLoaderAllocator() { WRAPPER_NO_CONTRACT; return SystemDomain::GetGlobalLoaderAllocator(); }
virtual PTR_AppDomain AsAppDomain()
{
LIMITED_METHOD_CONTRACT;
STATIC_CONTRACT_SO_TOLERANT;
_ASSERTE(!"Not an AppDomain");
return NULL;
}
static SharedDomain * GetDomain();
void Init();
void Terminate();
// This will also set the tenured bit if and only if the add was successful,
// and will make sure that the bit appears atomically set to all readers that
// might be accessing the hash on another thread.
MethodTable * FindIndexClass(SIZE_T index);
#ifdef FEATURE_LOADER_OPTIMIZATION
void AddShareableAssembly(Assembly * pAssembly);
class SharedAssemblyIterator
{
PtrHashMap::PtrIterator i;
Assembly * m_pAssembly;
public:
SharedAssemblyIterator() :
i(GetDomain() ? GetDomain()->m_assemblyMap.firstBucket() : NULL)
{ LIMITED_METHOD_DAC_CONTRACT; }
BOOL Next()
{
WRAPPER_NO_CONTRACT;
SUPPORTS_DAC;
if (i.end())
return FALSE;
m_pAssembly = PTR_Assembly(dac_cast<TADDR>(i.GetValue()));
++i;
return TRUE;
}
Assembly * GetAssembly()
{
LIMITED_METHOD_DAC_CONTRACT;
return m_pAssembly;
}
private:
friend class SharedDomain;
};
Assembly * FindShareableAssembly(SharedAssemblyLocator * pLocator);
SIZE_T GetShareableAssemblyCount();
#endif //FEATURE_LOADER_OPTIMIZATION
private:
friend class SharedAssemblyIterator;
friend class SharedFileLockHolder;
friend class ClrDataAccess;
#ifndef DACCESS_COMPILE
void *operator new(size_t size, void *pInPlace);
void operator delete(void *pMem);
#endif
SPTR_DECL(SharedDomain, m_pSharedDomain);
#ifdef FEATURE_LOADER_OPTIMIZATION
PEFileListLock m_FileCreateLock;
SIZE_T m_nextClassIndex;
PtrHashMap m_assemblyMap;
#endif
public:
#ifdef DACCESS_COMPILE
virtual void EnumMemoryRegions(CLRDataEnumMemoryFlags flags,
bool enumThis);
#endif
#ifdef FEATURE_LOADER_OPTIMIZATION
// Hash map comparison function`
static BOOL CompareSharedAssembly(UPTR u1, UPTR u2);
#endif
};
#ifdef FEATURE_LOADER_OPTIMIZATION
class SharedFileLockHolderBase : protected HolderBase<PEFile *>
{
protected:
PEFileListLock *m_pLock;
ListLockEntry *m_pLockElement;
SharedFileLockHolderBase(PEFile *value)
: HolderBase<PEFile *>(value)
{
LIMITED_METHOD_CONTRACT;
m_pLock = NULL;
m_pLockElement = NULL;
}
#ifndef DACCESS_COMPILE
void DoAcquire()
{
STATIC_CONTRACT_THROWS;
STATIC_CONTRACT_GC_TRIGGERS;
STATIC_CONTRACT_FAULT;
PEFileListLockHolder lockHolder(m_pLock);
m_pLockElement = m_pLock->FindFileLock(m_value);
if (m_pLockElement == NULL)
{
m_pLockElement = new ListLockEntry(m_pLock, m_value);
m_pLock->AddElement(m_pLockElement);
}
else
m_pLockElement->AddRef();
lockHolder.Release();
m_pLockElement->Enter();
}
void DoRelease()
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_TRIGGERS;
STATIC_CONTRACT_FORBID_FAULT;
m_pLockElement->Leave();
m_pLockElement->Release();
m_pLockElement = NULL;
}
#endif // DACCESS_COMPILE
};
class SharedFileLockHolder : public BaseHolder<PEFile *, SharedFileLockHolderBase>
{
public:
DEBUG_NOINLINE SharedFileLockHolder(SharedDomain *pDomain, PEFile *pFile, BOOL Take = TRUE)
: BaseHolder<PEFile *, SharedFileLockHolderBase>(pFile, FALSE)
{
STATIC_CONTRACT_THROWS;
STATIC_CONTRACT_GC_TRIGGERS;
STATIC_CONTRACT_FAULT;
ANNOTATION_SPECIAL_HOLDER_CALLER_NEEDS_DYNAMIC_CONTRACT;
m_pLock = &pDomain->m_FileCreateLock;
if (Take)
Acquire();
}
};
#endif // FEATURE_LOADER_OPTIMIZATION
inline BOOL BaseDomain::IsDefaultDomain()
{
LIMITED_METHOD_DAC_CONTRACT;
return (SystemDomain::System()->DefaultDomain() == this);
}
#include "comreflectioncache.inl"
#if !defined(DACCESS_COMPILE) && !defined(CROSSGEN_COMPILE)
// holds an extra reference so needs special Extract() and should not have SuppressRelease()
// Holders/Wrappers have nonvirtual methods so cannot use them as the base class
template <class AppDomainType>
class AppDomainCreationHolder
{
private:
// disable the copy ctor
AppDomainCreationHolder(const AppDomainCreationHolder<AppDomainType>&) {}
protected:
AppDomainType* m_pDomain;
BOOL m_bAcquired;
void ReleaseAppDomainDuringCreation()
{
CONTRACTL
{
NOTHROW;
WRAPPER(GC_TRIGGERS);
PRECONDITION(m_bAcquired);
PRECONDITION(CheckPointer(m_pDomain));
}
CONTRACTL_END;
if (m_pDomain->NotReadyForManagedCode())
{
m_pDomain->Release();
}
else
{
STRESS_LOG2 (LF_APPDOMAIN, LL_INFO100, "Unload domain during creation [%d] %p\n", m_pDomain->GetId().m_dwId, m_pDomain);
SystemDomain::MakeUnloadable(m_pDomain);
#ifdef _DEBUG
DWORD hostTestADUnload = g_pConfig->GetHostTestADUnload();
m_pDomain->EnableADUnloadWorker(hostTestADUnload != 2?EEPolicy::ADU_Safe:EEPolicy::ADU_Rude);
#else
m_pDomain->EnableADUnloadWorker(EEPolicy::ADU_Safe);
#endif
}
};
public:
AppDomainCreationHolder()
{
m_pDomain=NULL;
m_bAcquired=FALSE;
};
~AppDomainCreationHolder()
{
if (m_bAcquired)
{
Release();
}
};
void Assign(AppDomainType* pDomain)
{
if(m_bAcquired)
Release();
m_pDomain=pDomain;
if(m_pDomain)
{
AppDomain::RefTakerAcquire(m_pDomain);
#ifdef _DEBUG
m_pDomain->IncCreationCount();
#endif // _DEBUG
}
m_bAcquired=TRUE;
};
void Release()
{
_ASSERTE(m_bAcquired);
if(m_pDomain)
{
#ifdef _DEBUG
m_pDomain->DecCreationCount();
#endif // _DEBUG
if(!m_pDomain->IsDefaultDomain())
ReleaseAppDomainDuringCreation();
AppDomain::RefTakerRelease(m_pDomain);
};
m_bAcquired=FALSE;
};
AppDomainType* Extract()
{
_ASSERTE(m_bAcquired);
if(m_pDomain)
{
#ifdef _DEBUG
m_pDomain->DecCreationCount();
#endif // _DEBUG
AppDomain::RefTakerRelease(m_pDomain);
}
m_bAcquired=FALSE;
return m_pDomain;
};
AppDomainType* operator ->()
{
_ASSERTE(m_bAcquired);
return m_pDomain;
}
operator AppDomainType*()
{
_ASSERTE(m_bAcquired);
return m_pDomain;
}
void DoneCreating()
{
Extract();
}
};
#endif // !DACCESS_COMPILE && !CROSSGEN_COMPILE
#endif
| {
"content_hash": "3624d8405a47d84c54aff3c3c03d4a6d",
"timestamp": "",
"source": "github",
"line_count": 5376,
"max_line_length": 186,
"avg_line_length": 31.64546130952381,
"alnum_prop": 0.6444576372806038,
"repo_name": "Lucrecious/coreclr",
"id": "0ec336dffafb39f5e99b07a2d978c9978934f8f8",
"size": "170126",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/vm/appdomain.hpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "946153"
},
{
"name": "Awk",
"bytes": "5865"
},
{
"name": "Batchfile",
"bytes": "68521"
},
{
"name": "C",
"bytes": "6389746"
},
{
"name": "C#",
"bytes": "135748431"
},
{
"name": "C++",
"bytes": "68385569"
},
{
"name": "CMake",
"bytes": "560199"
},
{
"name": "Groff",
"bytes": "529523"
},
{
"name": "Groovy",
"bytes": "67970"
},
{
"name": "HTML",
"bytes": "16196"
},
{
"name": "Makefile",
"bytes": "2527"
},
{
"name": "Objective-C",
"bytes": "229760"
},
{
"name": "PAWN",
"bytes": "926"
},
{
"name": "Perl",
"bytes": "24550"
},
{
"name": "PowerShell",
"bytes": "9442"
},
{
"name": "Python",
"bytes": "81470"
},
{
"name": "Shell",
"bytes": "77659"
},
{
"name": "Smalltalk",
"bytes": "1497866"
},
{
"name": "SuperCollider",
"bytes": "4752"
},
{
"name": "Yacc",
"bytes": "157348"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html><head><meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>WinPcap: packet_file_header Struct Reference</title>
<link href="style.css" rel="stylesheet" type="text/css">
<link href="tabs.css" rel="stylesheet" type="text/css">
</head><body>
<!-- Generated by Doxygen 1.5.6 -->
<div class="navigation" id="top">
<div class="tabs">
<ul>
<li><a href="main.html"><span>Main Page</span></a></li>
<li><a href="pages.html"><span>Related Pages</span></a></li>
<li><a href="modules.html"><span>Modules</span></a></li>
<li class="current"><a href="annotated.html"><span>Data Structures</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
</ul>
</div>
<div class="tabs">
<ul>
<li><a href="annotated.html"><span>Data Structures</span></a></li>
<li><a href="functions.html"><span>Data Fields</span></a></li>
</ul>
</div>
</div>
<div class="contents">
<h1>packet_file_header Struct Reference<br>
<small>
[<a class="el" href="group__NPF__include.html">NPF structures and definitions</a>]</small>
</h1><!-- doxytag: class="packet_file_header" -->Header of a libpcap dump file.
<a href="#_details">More...</a>
<p>
<code>#include <<a class="el" href="Packet_8h-source.html">Packet.h</a>></code>
<p>
<table border="0" cellpadding="0" cellspacing="0">
<tr><td></td></tr>
<tr><td colspan="2"><br><h2>Data Fields</h2></td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top">UINT </td><td class="memItemRight" valign="bottom"><a class="el" href="structpacket__file__header.html#b396ddef34e11edb49e5edfcc39c2dc7">magic</a></td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Libpcap magic number. <a href="#b396ddef34e11edb49e5edfcc39c2dc7"></a><br></td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top">USHORT </td><td class="memItemRight" valign="bottom"><a class="el" href="structpacket__file__header.html#312dffcaa516df104318626fbdc01a77">version_major</a></td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Libpcap major version. <a href="#312dffcaa516df104318626fbdc01a77"></a><br></td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top">USHORT </td><td class="memItemRight" valign="bottom"><a class="el" href="structpacket__file__header.html#143bc467378ffbd0460662bd8912082b">version_minor</a></td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Libpcap minor version. <a href="#143bc467378ffbd0460662bd8912082b"></a><br></td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top">UINT </td><td class="memItemRight" valign="bottom"><a class="el" href="structpacket__file__header.html#b0f3e0ccc83861eb84cd3da32f01f090">thiszone</a></td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Gmt to local correction. <a href="#b0f3e0ccc83861eb84cd3da32f01f090"></a><br></td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top">UINT </td><td class="memItemRight" valign="bottom"><a class="el" href="structpacket__file__header.html#5938c470e9e548ad2ac04923725e7721">sigfigs</a></td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Accuracy of timestamps. <a href="#5938c470e9e548ad2ac04923725e7721"></a><br></td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top">UINT </td><td class="memItemRight" valign="bottom"><a class="el" href="structpacket__file__header.html#45b189420d67014dba25bd13da85ddae">snaplen</a></td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Length of the max saved portion of each packet. <a href="#45b189420d67014dba25bd13da85ddae"></a><br></td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top">UINT </td><td class="memItemRight" valign="bottom"><a class="el" href="structpacket__file__header.html#b2a8854181cde7a065a43380b56fd2a1">linktype</a></td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Data link type (DLT_*). See win_bpf.h for details. <a href="#b2a8854181cde7a065a43380b56fd2a1"></a><br></td></tr>
</table>
<hr><a name="_details"></a><h2>Detailed Description</h2>
Header of a libpcap dump file.
<p>
Used when a driver instance is set in dump mode to create a libpcap-compatible file.
<p>Definition at line <a class="el" href="Packet_8h-source.html#l00106">106</a> of file <a class="el" href="Packet_8h-source.html">Packet.h</a>.</p>
<hr><h2>Field Documentation</h2>
<a class="anchor" name="b396ddef34e11edb49e5edfcc39c2dc7"></a><!-- doxytag: member="packet_file_header::magic" ref="b396ddef34e11edb49e5edfcc39c2dc7" args="" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">UINT <a class="el" href="structpacket__file__header.html#b396ddef34e11edb49e5edfcc39c2dc7">magic</a> </td>
</tr>
</table>
</div>
<div class="memdoc">
<p>
Libpcap magic number.
<p>
<p>Definition at line <a class="el" href="Packet_8h-source.html#l00108">108</a> of file <a class="el" href="Packet_8h-source.html">Packet.h</a>.</p>
</div>
</div><p>
<a class="anchor" name="312dffcaa516df104318626fbdc01a77"></a><!-- doxytag: member="packet_file_header::version_major" ref="312dffcaa516df104318626fbdc01a77" args="" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">USHORT <a class="el" href="structpacket__file__header.html#312dffcaa516df104318626fbdc01a77">version_major</a> </td>
</tr>
</table>
</div>
<div class="memdoc">
<p>
Libpcap major version.
<p>
<p>Definition at line <a class="el" href="Packet_8h-source.html#l00109">109</a> of file <a class="el" href="Packet_8h-source.html">Packet.h</a>.</p>
</div>
</div><p>
<a class="anchor" name="143bc467378ffbd0460662bd8912082b"></a><!-- doxytag: member="packet_file_header::version_minor" ref="143bc467378ffbd0460662bd8912082b" args="" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">USHORT <a class="el" href="structpacket__file__header.html#143bc467378ffbd0460662bd8912082b">version_minor</a> </td>
</tr>
</table>
</div>
<div class="memdoc">
<p>
Libpcap minor version.
<p>
<p>Definition at line <a class="el" href="Packet_8h-source.html#l00110">110</a> of file <a class="el" href="Packet_8h-source.html">Packet.h</a>.</p>
</div>
</div><p>
<a class="anchor" name="b0f3e0ccc83861eb84cd3da32f01f090"></a><!-- doxytag: member="packet_file_header::thiszone" ref="b0f3e0ccc83861eb84cd3da32f01f090" args="" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">UINT <a class="el" href="structpacket__file__header.html#b0f3e0ccc83861eb84cd3da32f01f090">thiszone</a> </td>
</tr>
</table>
</div>
<div class="memdoc">
<p>
Gmt to local correction.
<p>
<p>Definition at line <a class="el" href="Packet_8h-source.html#l00111">111</a> of file <a class="el" href="Packet_8h-source.html">Packet.h</a>.</p>
</div>
</div><p>
<a class="anchor" name="5938c470e9e548ad2ac04923725e7721"></a><!-- doxytag: member="packet_file_header::sigfigs" ref="5938c470e9e548ad2ac04923725e7721" args="" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">UINT <a class="el" href="structpacket__file__header.html#5938c470e9e548ad2ac04923725e7721">sigfigs</a> </td>
</tr>
</table>
</div>
<div class="memdoc">
<p>
Accuracy of timestamps.
<p>
<p>Definition at line <a class="el" href="Packet_8h-source.html#l00112">112</a> of file <a class="el" href="Packet_8h-source.html">Packet.h</a>.</p>
</div>
</div><p>
<a class="anchor" name="45b189420d67014dba25bd13da85ddae"></a><!-- doxytag: member="packet_file_header::snaplen" ref="45b189420d67014dba25bd13da85ddae" args="" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">UINT <a class="el" href="structpacket__file__header.html#45b189420d67014dba25bd13da85ddae">snaplen</a> </td>
</tr>
</table>
</div>
<div class="memdoc">
<p>
Length of the max saved portion of each packet.
<p>
<p>Definition at line <a class="el" href="Packet_8h-source.html#l00113">113</a> of file <a class="el" href="Packet_8h-source.html">Packet.h</a>.</p>
</div>
</div><p>
<a class="anchor" name="b2a8854181cde7a065a43380b56fd2a1"></a><!-- doxytag: member="packet_file_header::linktype" ref="b2a8854181cde7a065a43380b56fd2a1" args="" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">UINT <a class="el" href="structpacket__file__header.html#b2a8854181cde7a065a43380b56fd2a1">linktype</a> </td>
</tr>
</table>
</div>
<div class="memdoc">
<p>
Data link type (DLT_*). See win_bpf.h for details.
<p>
<p>Definition at line <a class="el" href="Packet_8h-source.html#l00114">114</a> of file <a class="el" href="Packet_8h-source.html">Packet.h</a>.</p>
</div>
</div><p>
<hr>The documentation for this struct was generated from the following file:<ul>
<li><a class="el" href="Packet_8h-source.html">Packet.h</a></ul>
</div>
<hr>
<p align="right"><img border="0" src="winpcap_small.gif" align="absbottom" width="91" height="27">
documentation. Copyright (c) 2002-2005 Politecnico di Torino. Copyright (c) 2005-2009
CACE Technologies. All rights reserved.</p>
| {
"content_hash": "495d3a7a446fc5cfe6066011bb96c407",
"timestamp": "",
"source": "github",
"line_count": 205,
"max_line_length": 233,
"avg_line_length": 47.05853658536585,
"alnum_prop": 0.6729553228983104,
"repo_name": "gyakoo/pcapcigi",
"id": "27128d0bf88f0c2bd8e2e123e8c11d48184c3f23",
"size": "9647",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "wpcap/4.1.1/docs/html/structpacket__file__header.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "117016"
},
{
"name": "C++",
"bytes": "23065"
},
{
"name": "CSS",
"bytes": "9838"
},
{
"name": "HTML",
"bytes": "1982173"
}
],
"symlink_target": ""
} |
package mapapi.overlayutil;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.Overlay;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.Polyline;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.route.WalkingRouteLine;
import java.util.ArrayList;
import java.util.List;
/**
* 用于显示步行路线的overlay,自3.4.0版本起可实例化多个添加在地图中显示
*/
public class WalkingRouteOverlay extends OverlayManager {
private WalkingRouteLine mRouteLine = null;
public WalkingRouteOverlay(BaiduMap baiduMap) {
super(baiduMap);
}
/**
* 设置路线数据。
*
* @param line
* 路线数据
*/
public void setData(WalkingRouteLine line) {
mRouteLine = line;
}
@Override
public final List<OverlayOptions> getOverlayOptions() {
if (mRouteLine == null) {
return null;
}
List<OverlayOptions> overlayList = new ArrayList<OverlayOptions>();
if (mRouteLine.getAllStep() != null
&& mRouteLine.getAllStep().size() > 0) {
for (WalkingRouteLine.WalkingStep step : mRouteLine.getAllStep()) {
Bundle b = new Bundle();
b.putInt("index", mRouteLine.getAllStep().indexOf(step));
if (step.getEntrance() != null) {
overlayList.add((new MarkerOptions())
.position(step.getEntrance().getLocation())
.rotate((360 - step.getDirection()))
.zIndex(10)
.anchor(0.5f, 0.5f)
.extraInfo(b)
.icon(BitmapDescriptorFactory
.fromAssetWithDpi("Icon_line_node.png")));
}
// 最后路段绘制出口点
if (mRouteLine.getAllStep().indexOf(step) == (mRouteLine
.getAllStep().size() - 1) && step.getExit() != null) {
overlayList.add((new MarkerOptions())
.position(step.getExit().getLocation())
.anchor(0.5f, 0.5f)
.zIndex(10)
.icon(BitmapDescriptorFactory
.fromAssetWithDpi("Icon_line_node.png")));
}
}
}
// starting
if (mRouteLine.getStarting() != null) {
overlayList.add((new MarkerOptions())
.position(mRouteLine.getStarting().getLocation())
.icon(getStartMarker() != null ? getStartMarker() :
BitmapDescriptorFactory
.fromAssetWithDpi("Icon_start.png")).zIndex(10));
}
// terminal
if (mRouteLine.getTerminal() != null) {
overlayList
.add((new MarkerOptions())
.position(mRouteLine.getTerminal().getLocation())
.icon(getTerminalMarker() != null ? getTerminalMarker() :
BitmapDescriptorFactory
.fromAssetWithDpi("Icon_end.png"))
.zIndex(10));
}
// poly line list
if (mRouteLine.getAllStep() != null
&& mRouteLine.getAllStep().size() > 0) {
LatLng lastStepLastPoint = null;
for (WalkingRouteLine.WalkingStep step : mRouteLine.getAllStep()) {
List<LatLng> watPoints = step.getWayPoints();
if (watPoints != null) {
List<LatLng> points = new ArrayList<LatLng>();
if (lastStepLastPoint != null) {
points.add(lastStepLastPoint);
}
points.addAll(watPoints);
overlayList.add(new PolylineOptions().points(points).width(10)
.color(getLineColor() != 0 ? getLineColor() : Color.argb(178, 0, 78, 255)).zIndex(0));
lastStepLastPoint = watPoints.get(watPoints.size() - 1);
}
}
}
return overlayList;
}
/**
* 覆写此方法以改变默认起点图标
*
* @return 起点图标
*/
public BitmapDescriptor getStartMarker() {
return null;
}
public int getLineColor() {
return 0;
}
/**
* 覆写此方法以改变默认终点图标
*
* @return 终点图标
*/
public BitmapDescriptor getTerminalMarker() {
return null;
}
/**
* 处理点击事件
*
* @param i
* 被点击的step在
* {@link WalkingRouteLine#getAllStep()}
* 中的索引
* @return 是否处理了该点击事件
*/
public boolean onRouteNodeClick(int i) {
if (mRouteLine.getAllStep() != null
&& mRouteLine.getAllStep().get(i) != null) {
Log.i("baidumapsdk", "WalkingRouteOverlay onRouteNodeClick");
}
return false;
}
@Override
public final boolean onMarkerClick(Marker marker) {
for (Overlay mMarker : mOverlayList) {
if (mMarker instanceof Marker && mMarker.equals(marker)) {
if (marker.getExtraInfo() != null) {
onRouteNodeClick(marker.getExtraInfo().getInt("index"));
}
}
}
return true;
}
@Override
public boolean onPolylineClick(Polyline polyline) {
// TODO Auto-generated method stub
return false;
}
}
| {
"content_hash": "b574ffdb350107c8dac2123b5b61d314",
"timestamp": "",
"source": "github",
"line_count": 175,
"max_line_length": 118,
"avg_line_length": 35.245714285714286,
"alnum_prop": 0.49351491569390404,
"repo_name": "shuiliuxing/Cyclist",
"id": "1218316931fcaa8208620d11d9af7973407fd71e",
"size": "6386",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/java/mapapi/overlayutil/WalkingRouteOverlay.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "154"
},
{
"name": "Java",
"bytes": "294345"
}
],
"symlink_target": ""
} |
<?php
namespace PHPExiftool\Driver\Tag\DICOM;
use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;
/**
* @ExclusionPolicy("all")
*/
class VolumeLocalizationTechnique extends AbstractTag
{
protected $Id = '0018,9054';
protected $Name = 'VolumeLocalizationTechnique';
protected $FullName = 'DICOM::Main';
protected $GroupName = 'DICOM';
protected $g0 = 'DICOM';
protected $g1 = 'DICOM';
protected $g2 = 'Image';
protected $Type = '?';
protected $Writable = false;
protected $Description = 'Volume Localization Technique';
}
| {
"content_hash": "95c7098a3a2f9c720fa72bfecc622b8d",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 61,
"avg_line_length": 17.4,
"alnum_prop": 0.6814449917898193,
"repo_name": "romainneutron/PHPExiftool",
"id": "4b28b900c08eec6be996c303c7a206678e30c212",
"size": "831",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/PHPExiftool/Driver/Tag/DICOM/VolumeLocalizationTechnique.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "22042446"
}
],
"symlink_target": ""
} |
include_guard()
# General board information.
set(BOARD_ID 2)
set(BOARD_NAME "CCC rad1o-badge")
# Pull in the common code for the LPC4330.
include(${PATH_LIBGREAT_FIRMWARE_CMAKE}/platform/lpc4330.cmake)
| {
"content_hash": "3c484a88da599b54098965bfff527586",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 63,
"avg_line_length": 26,
"alnum_prop": 0.7451923076923077,
"repo_name": "greatscottgadgets/greatfet",
"id": "a7ccf5c45544d96536ad68f424bb8406541baf7b",
"size": "292",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "firmware/boards/rad1o_badge/board.cmake",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Assembly",
"bytes": "823"
},
{
"name": "C",
"bytes": "546689"
},
{
"name": "C++",
"bytes": "457321"
},
{
"name": "CMake",
"bytes": "20175"
},
{
"name": "Dockerfile",
"bytes": "601"
},
{
"name": "Makefile",
"bytes": "8176"
},
{
"name": "Python",
"bytes": "541237"
},
{
"name": "Shell",
"bytes": "2236"
}
],
"symlink_target": ""
} |
// NOTE: This file was generated by the ServiceGenerator.
// ----------------------------------------------------------------------------
// API:
// Game Services API (gameservices/v1)
// Description:
// Deploy and manage infrastructure for global multiplayer gaming experiences.
// Documentation:
// https://cloud.google.com/solutions/gaming/
#import <GoogleAPIClientForREST/GTLRObject.h>
#if GTLR_RUNTIME_VERSION != 3000
#error This file was generated by a different version of ServiceGenerator which is incompatible with this GTLR library source.
#endif
@class GTLRGameServices_AuditConfig;
@class GTLRGameServices_AuditLogConfig;
@class GTLRGameServices_AuthorizationLoggingOptions;
@class GTLRGameServices_Binding;
@class GTLRGameServices_CloudAuditOptions;
@class GTLRGameServices_Condition;
@class GTLRGameServices_CounterOptions;
@class GTLRGameServices_CustomField;
@class GTLRGameServices_DataAccessOptions;
@class GTLRGameServices_Expr;
@class GTLRGameServices_Location;
@class GTLRGameServices_Location_Labels;
@class GTLRGameServices_Location_Metadata;
@class GTLRGameServices_LogConfig;
@class GTLRGameServices_Operation;
@class GTLRGameServices_Operation_Metadata;
@class GTLRGameServices_Operation_Response;
@class GTLRGameServices_Policy;
@class GTLRGameServices_Rule;
@class GTLRGameServices_Status;
@class GTLRGameServices_Status_Details_Item;
// Generated comments include content from the discovery document; avoid them
// causing warnings since clang's checks are some what arbitrary.
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdocumentation"
NS_ASSUME_NONNULL_BEGIN
// ----------------------------------------------------------------------------
// Constants - For some of the classes' properties below.
// ----------------------------------------------------------------------------
// GTLRGameServices_AuditLogConfig.logType
/**
* Admin reads. Example: CloudIAM getIamPolicy
*
* Value: "ADMIN_READ"
*/
FOUNDATION_EXTERN NSString * const kGTLRGameServices_AuditLogConfig_LogType_AdminRead;
/**
* Data reads. Example: CloudSQL Users list
*
* Value: "DATA_READ"
*/
FOUNDATION_EXTERN NSString * const kGTLRGameServices_AuditLogConfig_LogType_DataRead;
/**
* Data writes. Example: CloudSQL Users create
*
* Value: "DATA_WRITE"
*/
FOUNDATION_EXTERN NSString * const kGTLRGameServices_AuditLogConfig_LogType_DataWrite;
/**
* Default case. Should never be this.
*
* Value: "LOG_TYPE_UNSPECIFIED"
*/
FOUNDATION_EXTERN NSString * const kGTLRGameServices_AuditLogConfig_LogType_LogTypeUnspecified;
// ----------------------------------------------------------------------------
// GTLRGameServices_AuthorizationLoggingOptions.permissionType
/**
* A read of admin (meta) data.
*
* Value: "ADMIN_READ"
*/
FOUNDATION_EXTERN NSString * const kGTLRGameServices_AuthorizationLoggingOptions_PermissionType_AdminRead;
/**
* A write of admin (meta) data.
*
* Value: "ADMIN_WRITE"
*/
FOUNDATION_EXTERN NSString * const kGTLRGameServices_AuthorizationLoggingOptions_PermissionType_AdminWrite;
/**
* A read of standard data.
*
* Value: "DATA_READ"
*/
FOUNDATION_EXTERN NSString * const kGTLRGameServices_AuthorizationLoggingOptions_PermissionType_DataRead;
/**
* A write of standard data.
*
* Value: "DATA_WRITE"
*/
FOUNDATION_EXTERN NSString * const kGTLRGameServices_AuthorizationLoggingOptions_PermissionType_DataWrite;
/**
* Default. Should not be used.
*
* Value: "PERMISSION_TYPE_UNSPECIFIED"
*/
FOUNDATION_EXTERN NSString * const kGTLRGameServices_AuthorizationLoggingOptions_PermissionType_PermissionTypeUnspecified;
// ----------------------------------------------------------------------------
// GTLRGameServices_CloudAuditOptions.logName
/**
* Corresponds to "cloudaudit.googleapis.com/activity"
*
* Value: "ADMIN_ACTIVITY"
*/
FOUNDATION_EXTERN NSString * const kGTLRGameServices_CloudAuditOptions_LogName_AdminActivity;
/**
* Corresponds to "cloudaudit.googleapis.com/data_access"
*
* Value: "DATA_ACCESS"
*/
FOUNDATION_EXTERN NSString * const kGTLRGameServices_CloudAuditOptions_LogName_DataAccess;
/**
* Default. Should not be used.
*
* Value: "UNSPECIFIED_LOG_NAME"
*/
FOUNDATION_EXTERN NSString * const kGTLRGameServices_CloudAuditOptions_LogName_UnspecifiedLogName;
// ----------------------------------------------------------------------------
// GTLRGameServices_Condition.iam
/**
* An approver (distinct from the requester) that has authorized this request.
* When used with IN, the condition indicates that one of the approvers
* associated with the request matches the specified principal, or is a member
* of the specified group. Approvers can only grant additional access, and are
* thus only used in a strictly positive context (e.g. ALLOW/IN or
* DENY/NOT_IN).
*
* Value: "APPROVER"
*/
FOUNDATION_EXTERN NSString * const kGTLRGameServices_Condition_Iam_Approver;
/**
* The principal (even if an authority selector is present), which must only be
* used for attribution, not authorization.
*
* Value: "ATTRIBUTION"
*/
FOUNDATION_EXTERN NSString * const kGTLRGameServices_Condition_Iam_Attribution;
/**
* Either principal or (if present) authority selector.
*
* Value: "AUTHORITY"
*/
FOUNDATION_EXTERN NSString * const kGTLRGameServices_Condition_Iam_Authority;
/**
* What type of credentials have been supplied with this request. String values
* should match enum names from security_loas_l2.CredentialsType - currently,
* only CREDS_TYPE_EMERGENCY is supported. It is not permitted to grant access
* based on the *absence* of a credentials type, so the conditions can only be
* used in a "positive" context (e.g., ALLOW/IN or DENY/NOT_IN).
*
* Value: "CREDENTIALS_TYPE"
*/
FOUNDATION_EXTERN NSString * const kGTLRGameServices_Condition_Iam_CredentialsType;
/**
* EXPERIMENTAL -- DO NOT USE. The conditions can only be used in a "positive"
* context (e.g., ALLOW/IN or DENY/NOT_IN).
*
* Value: "CREDS_ASSERTION"
*/
FOUNDATION_EXTERN NSString * const kGTLRGameServices_Condition_Iam_CredsAssertion;
/**
* What types of justifications have been supplied with this request. String
* values should match enum names from security.credentials.JustificationType,
* e.g. "MANUAL_STRING". It is not permitted to grant access based on the
* *absence* of a justification, so justification conditions can only be used
* in a "positive" context (e.g., ALLOW/IN or DENY/NOT_IN). Multiple
* justifications, e.g., a Buganizer ID and a manually-entered reason, are
* normal and supported.
*
* Value: "JUSTIFICATION_TYPE"
*/
FOUNDATION_EXTERN NSString * const kGTLRGameServices_Condition_Iam_JustificationType;
/**
* Default non-attribute.
*
* Value: "NO_ATTR"
*/
FOUNDATION_EXTERN NSString * const kGTLRGameServices_Condition_Iam_NoAttr;
/**
* Any of the security realms in the IAMContext (go/security-realms). When used
* with IN, the condition indicates "any of the request's realms match one of
* the given values; with NOT_IN, "none of the realms match any of the given
* values". Note that a value can be: - 'self:campus' (i.e., clients that are
* in the same campus) - 'self:metro' (i.e., clients that are in the same
* metro) - 'self:cloud-region' (i.e., allow connections from clients that are
* in the same cloud region) - 'self:prod-region' (i.e., allow connections from
* clients that are in the same prod region) - 'guardians' (i.e., allow
* connections from its guardian realms. See
* go/security-realms-glossary#guardian for more information.) - 'self'
* [DEPRECATED] (i.e., allow connections from clients that are in the same
* security realm, which is currently but not guaranteed to be campus-sized) -
* a realm (e.g., 'campus-abc') - a realm group (e.g.,
* 'realms-for-borg-cell-xx', see: go/realm-groups) A match is determined by a
* realm group membership check performed by a RealmAclRep object
* (go/realm-acl-howto). It is not permitted to grant access based on the
* *absence* of a realm, so realm conditions can only be used in a "positive"
* context (e.g., ALLOW/IN or DENY/NOT_IN).
*
* Value: "SECURITY_REALM"
*/
FOUNDATION_EXTERN NSString * const kGTLRGameServices_Condition_Iam_SecurityRealm;
// ----------------------------------------------------------------------------
// GTLRGameServices_Condition.op
/**
* Subject is discharged
*
* Value: "DISCHARGED"
*/
FOUNDATION_EXTERN NSString * const kGTLRGameServices_Condition_Op_Discharged;
/**
* DEPRECATED. Use IN instead.
*
* Value: "EQUALS"
*/
FOUNDATION_EXTERN NSString * const kGTLRGameServices_Condition_Op_Equals;
/**
* The condition is true if the subject (or any element of it if it is a set)
* matches any of the supplied values.
*
* Value: "IN"
*/
FOUNDATION_EXTERN NSString * const kGTLRGameServices_Condition_Op_In;
/**
* Default no-op.
*
* Value: "NO_OP"
*/
FOUNDATION_EXTERN NSString * const kGTLRGameServices_Condition_Op_NoOp;
/**
* DEPRECATED. Use NOT_IN instead.
*
* Value: "NOT_EQUALS"
*/
FOUNDATION_EXTERN NSString * const kGTLRGameServices_Condition_Op_NotEquals;
/**
* The condition is true if the subject (or every element of it if it is a set)
* matches none of the supplied values.
*
* Value: "NOT_IN"
*/
FOUNDATION_EXTERN NSString * const kGTLRGameServices_Condition_Op_NotIn;
// ----------------------------------------------------------------------------
// GTLRGameServices_Condition.sys
/**
* IP address of the caller
*
* Value: "IP"
*/
FOUNDATION_EXTERN NSString * const kGTLRGameServices_Condition_Sys_Ip;
/**
* Resource name
*
* Value: "NAME"
*/
FOUNDATION_EXTERN NSString * const kGTLRGameServices_Condition_Sys_Name;
/**
* Default non-attribute type
*
* Value: "NO_ATTR"
*/
FOUNDATION_EXTERN NSString * const kGTLRGameServices_Condition_Sys_NoAttr;
/**
* Region of the resource
*
* Value: "REGION"
*/
FOUNDATION_EXTERN NSString * const kGTLRGameServices_Condition_Sys_Region;
/**
* Service name
*
* Value: "SERVICE"
*/
FOUNDATION_EXTERN NSString * const kGTLRGameServices_Condition_Sys_Service;
// ----------------------------------------------------------------------------
// GTLRGameServices_DataAccessOptions.logMode
/**
* The application's operation in the context of which this authorization check
* is being made may only be performed if it is successfully logged to Gin. For
* instance, the authorization library may satisfy this obligation by emitting
* a partial log entry at authorization check time and only returning ALLOW to
* the application if it succeeds. If a matching Rule has this directive, but
* the client has not indicated that it will honor such requirements, then the
* IAM check will result in authorization failure by setting
* CheckPolicyResponse.success=false.
*
* Value: "LOG_FAIL_CLOSED"
*/
FOUNDATION_EXTERN NSString * const kGTLRGameServices_DataAccessOptions_LogMode_LogFailClosed;
/**
* Client is not required to write a partial Gin log immediately after the
* authorization check. If client chooses to write one and it fails, client may
* either fail open (allow the operation to continue) or fail closed (handle as
* a DENY outcome).
*
* Value: "LOG_MODE_UNSPECIFIED"
*/
FOUNDATION_EXTERN NSString * const kGTLRGameServices_DataAccessOptions_LogMode_LogModeUnspecified;
// ----------------------------------------------------------------------------
// GTLRGameServices_Rule.action
/**
* Matching 'Entries' grant access.
*
* Value: "ALLOW"
*/
FOUNDATION_EXTERN NSString * const kGTLRGameServices_Rule_Action_Allow;
/**
* Matching 'Entries' grant access and the caller promises to log the request
* per the returned log_configs.
*
* Value: "ALLOW_WITH_LOG"
*/
FOUNDATION_EXTERN NSString * const kGTLRGameServices_Rule_Action_AllowWithLog;
/**
* Matching 'Entries' deny access.
*
* Value: "DENY"
*/
FOUNDATION_EXTERN NSString * const kGTLRGameServices_Rule_Action_Deny;
/**
* Matching 'Entries' deny access and the caller promises to log the request
* per the returned log_configs.
*
* Value: "DENY_WITH_LOG"
*/
FOUNDATION_EXTERN NSString * const kGTLRGameServices_Rule_Action_DenyWithLog;
/**
* Matching 'Entries' tell IAM.Check callers to generate logs.
*
* Value: "LOG"
*/
FOUNDATION_EXTERN NSString * const kGTLRGameServices_Rule_Action_Log;
/**
* Default no action.
*
* Value: "NO_ACTION"
*/
FOUNDATION_EXTERN NSString * const kGTLRGameServices_Rule_Action_NoAction;
/**
* Specifies the audit configuration for a service. The configuration
* determines which permission types are logged, and what identities, if any,
* are exempted from logging. An AuditConfig must have one or more
* AuditLogConfigs. If there are AuditConfigs for both `allServices` and a
* specific service, the union of the two AuditConfigs is used for that
* service: the log_types specified in each AuditConfig are enabled, and the
* exempted_members in each AuditLogConfig are exempted. Example Policy with
* multiple AuditConfigs: { "audit_configs": [ { "service": "allServices",
* "audit_log_configs": [ { "log_type": "DATA_READ", "exempted_members": [
* "user:jose\@example.com" ] }, { "log_type": "DATA_WRITE" }, { "log_type":
* "ADMIN_READ" } ] }, { "service": "sampleservice.googleapis.com",
* "audit_log_configs": [ { "log_type": "DATA_READ" }, { "log_type":
* "DATA_WRITE", "exempted_members": [ "user:aliya\@example.com" ] } ] } ] }
* For sampleservice, this policy enables DATA_READ, DATA_WRITE and ADMIN_READ
* logging. It also exempts `jose\@example.com` from DATA_READ logging, and
* `aliya\@example.com` from DATA_WRITE logging.
*/
@interface GTLRGameServices_AuditConfig : GTLRObject
/** The configuration for logging of each type of permission. */
@property(nonatomic, strong, nullable) NSArray<GTLRGameServices_AuditLogConfig *> *auditLogConfigs;
/**
* Specifies a service that will be enabled for audit logging. For example,
* `storage.googleapis.com`, `cloudsql.googleapis.com`. `allServices` is a
* special value that covers all services.
*/
@property(nonatomic, copy, nullable) NSString *service;
@end
/**
* Provides the configuration for logging a type of permissions. Example: {
* "audit_log_configs": [ { "log_type": "DATA_READ", "exempted_members": [
* "user:jose\@example.com" ] }, { "log_type": "DATA_WRITE" } ] } This enables
* 'DATA_READ' and 'DATA_WRITE' logging, while exempting jose\@example.com from
* DATA_READ logging.
*/
@interface GTLRGameServices_AuditLogConfig : GTLRObject
/**
* Specifies the identities that do not cause logging for this type of
* permission. Follows the same format of Binding.members.
*/
@property(nonatomic, strong, nullable) NSArray<NSString *> *exemptedMembers;
/**
* ignoreChildExemptions
*
* Uses NSNumber of boolValue.
*/
@property(nonatomic, strong, nullable) NSNumber *ignoreChildExemptions;
/**
* The log type that this config enables.
*
* Likely values:
* @arg @c kGTLRGameServices_AuditLogConfig_LogType_AdminRead Admin reads.
* Example: CloudIAM getIamPolicy (Value: "ADMIN_READ")
* @arg @c kGTLRGameServices_AuditLogConfig_LogType_DataRead Data reads.
* Example: CloudSQL Users list (Value: "DATA_READ")
* @arg @c kGTLRGameServices_AuditLogConfig_LogType_DataWrite Data writes.
* Example: CloudSQL Users create (Value: "DATA_WRITE")
* @arg @c kGTLRGameServices_AuditLogConfig_LogType_LogTypeUnspecified
* Default case. Should never be this. (Value: "LOG_TYPE_UNSPECIFIED")
*/
@property(nonatomic, copy, nullable) NSString *logType;
@end
/**
* Authorization-related information used by Cloud Audit Logging.
*/
@interface GTLRGameServices_AuthorizationLoggingOptions : GTLRObject
/**
* The type of the permission that was checked.
*
* Likely values:
* @arg @c kGTLRGameServices_AuthorizationLoggingOptions_PermissionType_AdminRead
* A read of admin (meta) data. (Value: "ADMIN_READ")
* @arg @c kGTLRGameServices_AuthorizationLoggingOptions_PermissionType_AdminWrite
* A write of admin (meta) data. (Value: "ADMIN_WRITE")
* @arg @c kGTLRGameServices_AuthorizationLoggingOptions_PermissionType_DataRead
* A read of standard data. (Value: "DATA_READ")
* @arg @c kGTLRGameServices_AuthorizationLoggingOptions_PermissionType_DataWrite
* A write of standard data. (Value: "DATA_WRITE")
* @arg @c kGTLRGameServices_AuthorizationLoggingOptions_PermissionType_PermissionTypeUnspecified
* Default. Should not be used. (Value: "PERMISSION_TYPE_UNSPECIFIED")
*/
@property(nonatomic, copy, nullable) NSString *permissionType;
@end
/**
* Associates `members`, or principals, with a `role`.
*/
@interface GTLRGameServices_Binding : GTLRObject
@property(nonatomic, copy, nullable) NSString *bindingId;
/**
* The condition that is associated with this binding. If the condition
* evaluates to `true`, then this binding applies to the current request. If
* the condition evaluates to `false`, then this binding does not apply to the
* current request. However, a different role binding might grant the same role
* to one or more of the principals in this binding. To learn which resources
* support conditions in their IAM policies, see the [IAM
* documentation](https://cloud.google.com/iam/help/conditions/resource-policies).
*/
@property(nonatomic, strong, nullable) GTLRGameServices_Expr *condition;
/**
* Specifies the principals requesting access for a Google Cloud resource.
* `members` can have the following values: * `allUsers`: A special identifier
* that represents anyone who is on the internet; with or without a Google
* account. * `allAuthenticatedUsers`: A special identifier that represents
* anyone who is authenticated with a Google account or a service account. Does
* not include identities that come from external identity providers (IdPs)
* through identity federation. * `user:{emailid}`: An email address that
* represents a specific Google account. For example, `alice\@example.com` . *
* `serviceAccount:{emailid}`: An email address that represents a Google
* service account. For example, `my-other-app\@appspot.gserviceaccount.com`. *
* `serviceAccount:{projectid}.svc.id.goog[{namespace}/{kubernetes-sa}]`: An
* identifier for a [Kubernetes service
* account](https://cloud.google.com/kubernetes-engine/docs/how-to/kubernetes-service-accounts).
* For example, `my-project.svc.id.goog[my-namespace/my-kubernetes-sa]`. *
* `group:{emailid}`: An email address that represents a Google group. For
* example, `admins\@example.com`. * `deleted:user:{emailid}?uid={uniqueid}`:
* An email address (plus unique identifier) representing a user that has been
* recently deleted. For example,
* `alice\@example.com?uid=123456789012345678901`. If the user is recovered,
* this value reverts to `user:{emailid}` and the recovered user retains the
* role in the binding. * `deleted:serviceAccount:{emailid}?uid={uniqueid}`: An
* email address (plus unique identifier) representing a service account that
* has been recently deleted. For example,
* `my-other-app\@appspot.gserviceaccount.com?uid=123456789012345678901`. If
* the service account is undeleted, this value reverts to
* `serviceAccount:{emailid}` and the undeleted service account retains the
* role in the binding. * `deleted:group:{emailid}?uid={uniqueid}`: An email
* address (plus unique identifier) representing a Google group that has been
* recently deleted. For example,
* `admins\@example.com?uid=123456789012345678901`. If the group is recovered,
* this value reverts to `group:{emailid}` and the recovered group retains the
* role in the binding. * `domain:{domain}`: The G Suite domain (primary) that
* represents all the users of that domain. For example, `google.com` or
* `example.com`.
*/
@property(nonatomic, strong, nullable) NSArray<NSString *> *members;
/**
* Role that is assigned to the list of `members`, or principals. For example,
* `roles/viewer`, `roles/editor`, or `roles/owner`.
*/
@property(nonatomic, copy, nullable) NSString *role;
@end
/**
* The request message for Operations.CancelOperation.
*/
@interface GTLRGameServices_CancelOperationRequest : GTLRObject
@end
/**
* Write a Cloud Audit log
*/
@interface GTLRGameServices_CloudAuditOptions : GTLRObject
/** Information used by the Cloud Audit Logging pipeline. */
@property(nonatomic, strong, nullable) GTLRGameServices_AuthorizationLoggingOptions *authorizationLoggingOptions;
/**
* The log_name to populate in the Cloud Audit Record.
*
* Likely values:
* @arg @c kGTLRGameServices_CloudAuditOptions_LogName_AdminActivity
* Corresponds to "cloudaudit.googleapis.com/activity" (Value:
* "ADMIN_ACTIVITY")
* @arg @c kGTLRGameServices_CloudAuditOptions_LogName_DataAccess Corresponds
* to "cloudaudit.googleapis.com/data_access" (Value: "DATA_ACCESS")
* @arg @c kGTLRGameServices_CloudAuditOptions_LogName_UnspecifiedLogName
* Default. Should not be used. (Value: "UNSPECIFIED_LOG_NAME")
*/
@property(nonatomic, copy, nullable) NSString *logName;
@end
/**
* A condition to be met.
*/
@interface GTLRGameServices_Condition : GTLRObject
/**
* Trusted attributes supplied by the IAM system.
*
* Likely values:
* @arg @c kGTLRGameServices_Condition_Iam_Approver An approver (distinct
* from the requester) that has authorized this request. When used with
* IN, the condition indicates that one of the approvers associated with
* the request matches the specified principal, or is a member of the
* specified group. Approvers can only grant additional access, and are
* thus only used in a strictly positive context (e.g. ALLOW/IN or
* DENY/NOT_IN). (Value: "APPROVER")
* @arg @c kGTLRGameServices_Condition_Iam_Attribution The principal (even if
* an authority selector is present), which must only be used for
* attribution, not authorization. (Value: "ATTRIBUTION")
* @arg @c kGTLRGameServices_Condition_Iam_Authority Either principal or (if
* present) authority selector. (Value: "AUTHORITY")
* @arg @c kGTLRGameServices_Condition_Iam_CredentialsType What type of
* credentials have been supplied with this request. String values should
* match enum names from security_loas_l2.CredentialsType - currently,
* only CREDS_TYPE_EMERGENCY is supported. It is not permitted to grant
* access based on the *absence* of a credentials type, so the conditions
* can only be used in a "positive" context (e.g., ALLOW/IN or
* DENY/NOT_IN). (Value: "CREDENTIALS_TYPE")
* @arg @c kGTLRGameServices_Condition_Iam_CredsAssertion EXPERIMENTAL -- DO
* NOT USE. The conditions can only be used in a "positive" context
* (e.g., ALLOW/IN or DENY/NOT_IN). (Value: "CREDS_ASSERTION")
* @arg @c kGTLRGameServices_Condition_Iam_JustificationType What types of
* justifications have been supplied with this request. String values
* should match enum names from security.credentials.JustificationType,
* e.g. "MANUAL_STRING". It is not permitted to grant access based on the
* *absence* of a justification, so justification conditions can only be
* used in a "positive" context (e.g., ALLOW/IN or DENY/NOT_IN). Multiple
* justifications, e.g., a Buganizer ID and a manually-entered reason,
* are normal and supported. (Value: "JUSTIFICATION_TYPE")
* @arg @c kGTLRGameServices_Condition_Iam_NoAttr Default non-attribute.
* (Value: "NO_ATTR")
* @arg @c kGTLRGameServices_Condition_Iam_SecurityRealm Any of the security
* realms in the IAMContext (go/security-realms). When used with IN, the
* condition indicates "any of the request's realms match one of the
* given values; with NOT_IN, "none of the realms match any of the given
* values". Note that a value can be: - 'self:campus' (i.e., clients that
* are in the same campus) - 'self:metro' (i.e., clients that are in the
* same metro) - 'self:cloud-region' (i.e., allow connections from
* clients that are in the same cloud region) - 'self:prod-region' (i.e.,
* allow connections from clients that are in the same prod region) -
* 'guardians' (i.e., allow connections from its guardian realms. See
* go/security-realms-glossary#guardian for more information.) - 'self'
* [DEPRECATED] (i.e., allow connections from clients that are in the
* same security realm, which is currently but not guaranteed to be
* campus-sized) - a realm (e.g., 'campus-abc') - a realm group (e.g.,
* 'realms-for-borg-cell-xx', see: go/realm-groups) A match is determined
* by a realm group membership check performed by a RealmAclRep object
* (go/realm-acl-howto). It is not permitted to grant access based on the
* *absence* of a realm, so realm conditions can only be used in a
* "positive" context (e.g., ALLOW/IN or DENY/NOT_IN). (Value:
* "SECURITY_REALM")
*/
@property(nonatomic, copy, nullable) NSString *iam;
/**
* An operator to apply the subject with.
*
* Likely values:
* @arg @c kGTLRGameServices_Condition_Op_Discharged Subject is discharged
* (Value: "DISCHARGED")
* @arg @c kGTLRGameServices_Condition_Op_Equals DEPRECATED. Use IN instead.
* (Value: "EQUALS")
* @arg @c kGTLRGameServices_Condition_Op_In The condition is true if the
* subject (or any element of it if it is a set) matches any of the
* supplied values. (Value: "IN")
* @arg @c kGTLRGameServices_Condition_Op_NoOp Default no-op. (Value:
* "NO_OP")
* @arg @c kGTLRGameServices_Condition_Op_NotEquals DEPRECATED. Use NOT_IN
* instead. (Value: "NOT_EQUALS")
* @arg @c kGTLRGameServices_Condition_Op_NotIn The condition is true if the
* subject (or every element of it if it is a set) matches none of the
* supplied values. (Value: "NOT_IN")
*/
@property(nonatomic, copy, nullable) NSString *op;
/** Trusted attributes discharged by the service. */
@property(nonatomic, copy, nullable) NSString *svc;
/**
* Trusted attributes supplied by any service that owns resources and uses the
* IAM system for access control.
*
* Likely values:
* @arg @c kGTLRGameServices_Condition_Sys_Ip IP address of the caller
* (Value: "IP")
* @arg @c kGTLRGameServices_Condition_Sys_Name Resource name (Value: "NAME")
* @arg @c kGTLRGameServices_Condition_Sys_NoAttr Default non-attribute type
* (Value: "NO_ATTR")
* @arg @c kGTLRGameServices_Condition_Sys_Region Region of the resource
* (Value: "REGION")
* @arg @c kGTLRGameServices_Condition_Sys_Service Service name (Value:
* "SERVICE")
*/
@property(nonatomic, copy, nullable) NSString *sys;
/** The objects of the condition. */
@property(nonatomic, strong, nullable) NSArray<NSString *> *values;
@end
/**
* Increment a streamz counter with the specified metric and field names.
* Metric names should start with a '/', generally be lowercase-only, and end
* in "_count". Field names should not contain an initial slash. The actual
* exported metric names will have "/iam/policy" prepended. Field names
* correspond to IAM request parameters and field values are their respective
* values. Supported field names: - "authority", which is "[token]" if
* IAMContext.token is present, otherwise the value of
* IAMContext.authority_selector if present, and otherwise a representation of
* IAMContext.principal; or - "iam_principal", a representation of
* IAMContext.principal even if a token or authority selector is present; or -
* "" (empty string), resulting in a counter with no fields. Examples: counter
* { metric: "/debug_access_count" field: "iam_principal" } ==> increment
* counter /iam/policy/debug_access_count {iam_principal=[value of
* IAMContext.principal]}
*/
@interface GTLRGameServices_CounterOptions : GTLRObject
/** Custom fields. */
@property(nonatomic, strong, nullable) NSArray<GTLRGameServices_CustomField *> *customFields;
/** The field value to attribute. */
@property(nonatomic, copy, nullable) NSString *field;
/** The metric to update. */
@property(nonatomic, copy, nullable) NSString *metric;
@end
/**
* Custom fields. These can be used to create a counter with arbitrary
* field/value pairs. See: go/rpcsp-custom-fields.
*/
@interface GTLRGameServices_CustomField : GTLRObject
/** Name is the field name. */
@property(nonatomic, copy, nullable) NSString *name;
/**
* Value is the field value. It is important that in contrast to the
* CounterOptions.field, the value here is a constant that is not derived from
* the IAMContext.
*/
@property(nonatomic, copy, nullable) NSString *value;
@end
/**
* Write a Data Access (Gin) log
*/
@interface GTLRGameServices_DataAccessOptions : GTLRObject
/**
* logMode
*
* Likely values:
* @arg @c kGTLRGameServices_DataAccessOptions_LogMode_LogFailClosed The
* application's operation in the context of which this authorization
* check is being made may only be performed if it is successfully logged
* to Gin. For instance, the authorization library may satisfy this
* obligation by emitting a partial log entry at authorization check time
* and only returning ALLOW to the application if it succeeds. If a
* matching Rule has this directive, but the client has not indicated
* that it will honor such requirements, then the IAM check will result
* in authorization failure by setting CheckPolicyResponse.success=false.
* (Value: "LOG_FAIL_CLOSED")
* @arg @c kGTLRGameServices_DataAccessOptions_LogMode_LogModeUnspecified
* Client is not required to write a partial Gin log immediately after
* the authorization check. If client chooses to write one and it fails,
* client may either fail open (allow the operation to continue) or fail
* closed (handle as a DENY outcome). (Value: "LOG_MODE_UNSPECIFIED")
*/
@property(nonatomic, copy, nullable) NSString *logMode;
@end
/**
* A generic empty message that you can re-use to avoid defining duplicated
* empty messages in your APIs. A typical example is to use it as the request
* or the response type of an API method. For instance: service Foo { rpc
* Bar(google.protobuf.Empty) returns (google.protobuf.Empty); }
*/
@interface GTLRGameServices_Empty : GTLRObject
@end
/**
* Represents a textual expression in the Common Expression Language (CEL)
* syntax. CEL is a C-like expression language. The syntax and semantics of CEL
* are documented at https://github.com/google/cel-spec. Example (Comparison):
* title: "Summary size limit" description: "Determines if a summary is less
* than 100 chars" expression: "document.summary.size() < 100" Example
* (Equality): title: "Requestor is owner" description: "Determines if
* requestor is the document owner" expression: "document.owner ==
* request.auth.claims.email" Example (Logic): title: "Public documents"
* description: "Determine whether the document should be publicly visible"
* expression: "document.type != 'private' && document.type != 'internal'"
* Example (Data Manipulation): title: "Notification string" description:
* "Create a notification string with a timestamp." expression: "'New message
* received at ' + string(document.create_time)" The exact variables and
* functions that may be referenced within an expression are determined by the
* service that evaluates it. See the service documentation for additional
* information.
*/
@interface GTLRGameServices_Expr : GTLRObject
/**
* Optional. Description of the expression. This is a longer text which
* describes the expression, e.g. when hovered over it in a UI.
*
* Remapped to 'descriptionProperty' to avoid NSObject's 'description'.
*/
@property(nonatomic, copy, nullable) NSString *descriptionProperty;
/**
* Textual representation of an expression in Common Expression Language
* syntax.
*/
@property(nonatomic, copy, nullable) NSString *expression;
/**
* Optional. String indicating the location of the expression for error
* reporting, e.g. a file name and a position in the file.
*/
@property(nonatomic, copy, nullable) NSString *location;
/**
* Optional. Title for the expression, i.e. a short string describing its
* purpose. This can be used e.g. in UIs which allow to enter the expression.
*/
@property(nonatomic, copy, nullable) NSString *title;
@end
/**
* The response message for Locations.ListLocations.
*
* @note This class supports NSFastEnumeration and indexed subscripting over
* its "locations" property. If returned as the result of a query, it
* should support automatic pagination (when @c shouldFetchNextPages is
* enabled).
*/
@interface GTLRGameServices_ListLocationsResponse : GTLRCollectionObject
/**
* A list of locations that matches the specified filter in the request.
*
* @note This property is used to support NSFastEnumeration and indexed
* subscripting on this class.
*/
@property(nonatomic, strong, nullable) NSArray<GTLRGameServices_Location *> *locations;
/** The standard List next-page token. */
@property(nonatomic, copy, nullable) NSString *nextPageToken;
@end
/**
* The response message for Operations.ListOperations.
*
* @note This class supports NSFastEnumeration and indexed subscripting over
* its "operations" property. If returned as the result of a query, it
* should support automatic pagination (when @c shouldFetchNextPages is
* enabled).
*/
@interface GTLRGameServices_ListOperationsResponse : GTLRCollectionObject
/** The standard List next-page token. */
@property(nonatomic, copy, nullable) NSString *nextPageToken;
/**
* A list of operations that matches the specified filter in the request.
*
* @note This property is used to support NSFastEnumeration and indexed
* subscripting on this class.
*/
@property(nonatomic, strong, nullable) NSArray<GTLRGameServices_Operation *> *operations;
@end
/**
* A resource that represents Google Cloud Platform location.
*/
@interface GTLRGameServices_Location : GTLRObject
/**
* The friendly name for this location, typically a nearby city name. For
* example, "Tokyo".
*/
@property(nonatomic, copy, nullable) NSString *displayName;
/**
* Cross-service attributes for the location. For example
* {"cloud.googleapis.com/region": "us-east1"}
*/
@property(nonatomic, strong, nullable) GTLRGameServices_Location_Labels *labels;
/** The canonical id for this location. For example: `"us-east1"`. */
@property(nonatomic, copy, nullable) NSString *locationId;
/**
* Service-specific metadata. For example the available capacity at the given
* location.
*/
@property(nonatomic, strong, nullable) GTLRGameServices_Location_Metadata *metadata;
/**
* Resource name for the location, which may vary between implementations. For
* example: `"projects/example-project/locations/us-east1"`
*/
@property(nonatomic, copy, nullable) NSString *name;
@end
/**
* Cross-service attributes for the location. For example
* {"cloud.googleapis.com/region": "us-east1"}
*
* @note This class is documented as having more properties of NSString. Use @c
* -additionalJSONKeys and @c -additionalPropertyForName: to get the list
* of properties and then fetch them; or @c -additionalProperties to
* fetch them all at once.
*/
@interface GTLRGameServices_Location_Labels : GTLRObject
@end
/**
* Service-specific metadata. For example the available capacity at the given
* location.
*
* @note This class is documented as having more properties of any valid JSON
* type. Use @c -additionalJSONKeys and @c -additionalPropertyForName: to
* get the list of properties and then fetch them; or @c
* -additionalProperties to fetch them all at once.
*/
@interface GTLRGameServices_Location_Metadata : GTLRObject
@end
/**
* Specifies what kind of log the caller must write
*/
@interface GTLRGameServices_LogConfig : GTLRObject
/** Cloud audit options. */
@property(nonatomic, strong, nullable) GTLRGameServices_CloudAuditOptions *cloudAudit;
/** Counter options. */
@property(nonatomic, strong, nullable) GTLRGameServices_CounterOptions *counter;
/** Data access options. */
@property(nonatomic, strong, nullable) GTLRGameServices_DataAccessOptions *dataAccess;
@end
/**
* This resource represents a long-running operation that is the result of a
* network API call.
*/
@interface GTLRGameServices_Operation : GTLRObject
/**
* If the value is `false`, it means the operation is still in progress. If
* `true`, the operation is completed, and either `error` or `response` is
* available.
*
* Uses NSNumber of boolValue.
*/
@property(nonatomic, strong, nullable) NSNumber *done;
/** The error result of the operation in case of failure or cancellation. */
@property(nonatomic, strong, nullable) GTLRGameServices_Status *error;
/**
* Service-specific metadata associated with the operation. It typically
* contains progress information and common metadata such as create time. Some
* services might not provide such metadata. Any method that returns a
* long-running operation should document the metadata type, if any.
*/
@property(nonatomic, strong, nullable) GTLRGameServices_Operation_Metadata *metadata;
/**
* The server-assigned name, which is only unique within the same service that
* originally returns it. If you use the default HTTP mapping, the `name`
* should be a resource name ending with `operations/{unique_id}`.
*/
@property(nonatomic, copy, nullable) NSString *name;
/**
* The normal response of the operation in case of success. If the original
* method returns no data on success, such as `Delete`, the response is
* `google.protobuf.Empty`. If the original method is standard
* `Get`/`Create`/`Update`, the response should be the resource. For other
* methods, the response should have the type `XxxResponse`, where `Xxx` is the
* original method name. For example, if the original method name is
* `TakeSnapshot()`, the inferred response type is `TakeSnapshotResponse`.
*/
@property(nonatomic, strong, nullable) GTLRGameServices_Operation_Response *response;
@end
/**
* Service-specific metadata associated with the operation. It typically
* contains progress information and common metadata such as create time. Some
* services might not provide such metadata. Any method that returns a
* long-running operation should document the metadata type, if any.
*
* @note This class is documented as having more properties of any valid JSON
* type. Use @c -additionalJSONKeys and @c -additionalPropertyForName: to
* get the list of properties and then fetch them; or @c
* -additionalProperties to fetch them all at once.
*/
@interface GTLRGameServices_Operation_Metadata : GTLRObject
@end
/**
* The normal response of the operation in case of success. If the original
* method returns no data on success, such as `Delete`, the response is
* `google.protobuf.Empty`. If the original method is standard
* `Get`/`Create`/`Update`, the response should be the resource. For other
* methods, the response should have the type `XxxResponse`, where `Xxx` is the
* original method name. For example, if the original method name is
* `TakeSnapshot()`, the inferred response type is `TakeSnapshotResponse`.
*
* @note This class is documented as having more properties of any valid JSON
* type. Use @c -additionalJSONKeys and @c -additionalPropertyForName: to
* get the list of properties and then fetch them; or @c
* -additionalProperties to fetch them all at once.
*/
@interface GTLRGameServices_Operation_Response : GTLRObject
@end
/**
* An Identity and Access Management (IAM) policy, which specifies access
* controls for Google Cloud resources. A `Policy` is a collection of
* `bindings`. A `binding` binds one or more `members`, or principals, to a
* single `role`. Principals can be user accounts, service accounts, Google
* groups, and domains (such as G Suite). A `role` is a named list of
* permissions; each `role` can be an IAM predefined role or a user-created
* custom role. For some types of Google Cloud resources, a `binding` can also
* specify a `condition`, which is a logical expression that allows access to a
* resource only if the expression evaluates to `true`. A condition can add
* constraints based on attributes of the request, the resource, or both. To
* learn which resources support conditions in their IAM policies, see the [IAM
* documentation](https://cloud.google.com/iam/help/conditions/resource-policies).
* **JSON example:** { "bindings": [ { "role":
* "roles/resourcemanager.organizationAdmin", "members": [
* "user:mike\@example.com", "group:admins\@example.com", "domain:google.com",
* "serviceAccount:my-project-id\@appspot.gserviceaccount.com" ] }, { "role":
* "roles/resourcemanager.organizationViewer", "members": [
* "user:eve\@example.com" ], "condition": { "title": "expirable access",
* "description": "Does not grant access after Sep 2020", "expression":
* "request.time < timestamp('2020-10-01T00:00:00.000Z')", } } ], "etag":
* "BwWWja0YfJA=", "version": 3 } **YAML example:** bindings: - members: -
* user:mike\@example.com - group:admins\@example.com - domain:google.com -
* serviceAccount:my-project-id\@appspot.gserviceaccount.com role:
* roles/resourcemanager.organizationAdmin - members: - user:eve\@example.com
* role: roles/resourcemanager.organizationViewer condition: title: expirable
* access description: Does not grant access after Sep 2020 expression:
* request.time < timestamp('2020-10-01T00:00:00.000Z') etag: BwWWja0YfJA=
* version: 3 For a description of IAM and its features, see the [IAM
* documentation](https://cloud.google.com/iam/docs/).
*/
@interface GTLRGameServices_Policy : GTLRObject
/** Specifies cloud audit logging configuration for this policy. */
@property(nonatomic, strong, nullable) NSArray<GTLRGameServices_AuditConfig *> *auditConfigs;
/**
* Associates a list of `members`, or principals, with a `role`. Optionally,
* may specify a `condition` that determines how and when the `bindings` are
* applied. Each of the `bindings` must contain at least one principal. The
* `bindings` in a `Policy` can refer to up to 1,500 principals; up to 250 of
* these principals can be Google groups. Each occurrence of a principal counts
* towards these limits. For example, if the `bindings` grant 50 different
* roles to `user:alice\@example.com`, and not to any other principal, then you
* can add another 1,450 principals to the `bindings` in the `Policy`.
*/
@property(nonatomic, strong, nullable) NSArray<GTLRGameServices_Binding *> *bindings;
/**
* `etag` is used for optimistic concurrency control as a way to help prevent
* simultaneous updates of a policy from overwriting each other. It is strongly
* suggested that systems make use of the `etag` in the read-modify-write cycle
* to perform policy updates in order to avoid race conditions: An `etag` is
* returned in the response to `getIamPolicy`, and systems are expected to put
* that etag in the request to `setIamPolicy` to ensure that their change will
* be applied to the same version of the policy. **Important:** If you use IAM
* Conditions, you must include the `etag` field whenever you call
* `setIamPolicy`. If you omit this field, then IAM allows you to overwrite a
* version `3` policy with a version `1` policy, and all of the conditions in
* the version `3` policy are lost.
*
* Contains encoded binary data; GTLRBase64 can encode/decode (probably
* web-safe format).
*/
@property(nonatomic, copy, nullable) NSString *ETag;
/**
* If more than one rule is specified, the rules are applied in the following
* manner: - All matching LOG rules are always applied. - If any
* DENY/DENY_WITH_LOG rule matches, permission is denied. Logging will be
* applied if one or more matching rule requires logging. - Otherwise, if any
* ALLOW/ALLOW_WITH_LOG rule matches, permission is granted. Logging will be
* applied if one or more matching rule requires logging. - Otherwise, if no
* rule applies, permission is denied.
*/
@property(nonatomic, strong, nullable) NSArray<GTLRGameServices_Rule *> *rules;
/**
* Specifies the format of the policy. Valid values are `0`, `1`, and `3`.
* Requests that specify an invalid value are rejected. Any operation that
* affects conditional role bindings must specify version `3`. This requirement
* applies to the following operations: * Getting a policy that includes a
* conditional role binding * Adding a conditional role binding to a policy *
* Changing a conditional role binding in a policy * Removing any role binding,
* with or without a condition, from a policy that includes conditions
* **Important:** If you use IAM Conditions, you must include the `etag` field
* whenever you call `setIamPolicy`. If you omit this field, then IAM allows
* you to overwrite a version `3` policy with a version `1` policy, and all of
* the conditions in the version `3` policy are lost. If a policy does not
* include any conditions, operations on that policy may specify any valid
* version or leave the field unset. To learn which resources support
* conditions in their IAM policies, see the [IAM
* documentation](https://cloud.google.com/iam/help/conditions/resource-policies).
*
* Uses NSNumber of intValue.
*/
@property(nonatomic, strong, nullable) NSNumber *version;
@end
/**
* A rule to be applied in a Policy.
*/
@interface GTLRGameServices_Rule : GTLRObject
/**
* Required
*
* Likely values:
* @arg @c kGTLRGameServices_Rule_Action_Allow Matching 'Entries' grant
* access. (Value: "ALLOW")
* @arg @c kGTLRGameServices_Rule_Action_AllowWithLog Matching 'Entries'
* grant access and the caller promises to log the request per the
* returned log_configs. (Value: "ALLOW_WITH_LOG")
* @arg @c kGTLRGameServices_Rule_Action_Deny Matching 'Entries' deny access.
* (Value: "DENY")
* @arg @c kGTLRGameServices_Rule_Action_DenyWithLog Matching 'Entries' deny
* access and the caller promises to log the request per the returned
* log_configs. (Value: "DENY_WITH_LOG")
* @arg @c kGTLRGameServices_Rule_Action_Log Matching 'Entries' tell
* IAM.Check callers to generate logs. (Value: "LOG")
* @arg @c kGTLRGameServices_Rule_Action_NoAction Default no action. (Value:
* "NO_ACTION")
*/
@property(nonatomic, copy, nullable) NSString *action;
/**
* Additional restrictions that must be met. All conditions must pass for the
* rule to match.
*/
@property(nonatomic, strong, nullable) NSArray<GTLRGameServices_Condition *> *conditions;
/**
* Human-readable description of the rule.
*
* Remapped to 'descriptionProperty' to avoid NSObject's 'description'.
*/
@property(nonatomic, copy, nullable) NSString *descriptionProperty;
/**
* If one or more 'in' clauses are specified, the rule matches if the
* PRINCIPAL/AUTHORITY_SELECTOR is in at least one of these entries.
*
* Remapped to 'inProperty' to avoid language reserved word 'in'.
*/
@property(nonatomic, strong, nullable) NSArray<NSString *> *inProperty;
/**
* The config returned to callers of CheckPolicy for any entries that match the
* LOG action.
*/
@property(nonatomic, strong, nullable) NSArray<GTLRGameServices_LogConfig *> *logConfig;
/**
* If one or more 'not_in' clauses are specified, the rule matches if the
* PRINCIPAL/AUTHORITY_SELECTOR is in none of the entries. The format for in
* and not_in entries can be found at in the Local IAM documentation (see
* go/local-iam#features).
*/
@property(nonatomic, strong, nullable) NSArray<NSString *> *notIn;
/**
* A permission is a string of form '..' (e.g., 'storage.buckets.list'). A
* value of '*' matches all permissions, and a verb part of '*' (e.g.,
* 'storage.buckets.*') matches all verbs.
*/
@property(nonatomic, strong, nullable) NSArray<NSString *> *permissions;
@end
/**
* Request message for `SetIamPolicy` method.
*/
@interface GTLRGameServices_SetIamPolicyRequest : GTLRObject
/**
* REQUIRED: The complete policy to be applied to the `resource`. The size of
* the policy is limited to a few 10s of KB. An empty policy is a valid policy
* but certain Google Cloud services (such as Projects) might reject them.
*/
@property(nonatomic, strong, nullable) GTLRGameServices_Policy *policy;
/**
* OPTIONAL: A FieldMask specifying which fields of the policy to modify. Only
* the fields in the mask will be modified. If no mask is provided, the
* following default mask is used: `paths: "bindings, etag"`
*
* String format is a comma-separated list of fields.
*/
@property(nonatomic, copy, nullable) NSString *updateMask;
@end
/**
* The `Status` type defines a logical error model that is suitable for
* different programming environments, including REST APIs and RPC APIs. It is
* used by [gRPC](https://github.com/grpc). Each `Status` message contains
* three pieces of data: error code, error message, and error details. You can
* find out more about this error model and how to work with it in the [API
* Design Guide](https://cloud.google.com/apis/design/errors).
*/
@interface GTLRGameServices_Status : GTLRObject
/**
* The status code, which should be an enum value of google.rpc.Code.
*
* Uses NSNumber of intValue.
*/
@property(nonatomic, strong, nullable) NSNumber *code;
/**
* A list of messages that carry the error details. There is a common set of
* message types for APIs to use.
*/
@property(nonatomic, strong, nullable) NSArray<GTLRGameServices_Status_Details_Item *> *details;
/**
* A developer-facing error message, which should be in English. Any
* user-facing error message should be localized and sent in the
* google.rpc.Status.details field, or localized by the client.
*/
@property(nonatomic, copy, nullable) NSString *message;
@end
/**
* GTLRGameServices_Status_Details_Item
*
* @note This class is documented as having more properties of any valid JSON
* type. Use @c -additionalJSONKeys and @c -additionalPropertyForName: to
* get the list of properties and then fetch them; or @c
* -additionalProperties to fetch them all at once.
*/
@interface GTLRGameServices_Status_Details_Item : GTLRObject
@end
/**
* Request message for `TestIamPermissions` method.
*/
@interface GTLRGameServices_TestIamPermissionsRequest : GTLRObject
/**
* The set of permissions to check for the `resource`. Permissions with
* wildcards (such as `*` or `storage.*`) are not allowed. For more information
* see [IAM Overview](https://cloud.google.com/iam/docs/overview#permissions).
*/
@property(nonatomic, strong, nullable) NSArray<NSString *> *permissions;
@end
/**
* Response message for `TestIamPermissions` method.
*/
@interface GTLRGameServices_TestIamPermissionsResponse : GTLRObject
/**
* A subset of `TestPermissionsRequest.permissions` that the caller is allowed.
*/
@property(nonatomic, strong, nullable) NSArray<NSString *> *permissions;
@end
NS_ASSUME_NONNULL_END
#pragma clang diagnostic pop
| {
"content_hash": "c2b71ae53538adc581d4a5f5ddfd6e63",
"timestamp": "",
"source": "github",
"line_count": 1283,
"max_line_length": 126,
"avg_line_length": 40.355416991426345,
"alnum_prop": 0.7152734857849197,
"repo_name": "google/google-api-objectivec-client-for-rest",
"id": "ca55aba6810600143069c38ad2260380a3d1a021",
"size": "51776",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "Sources/GeneratedServices/GameServices/Public/GoogleAPIClientForREST/GTLRGameServicesObjects.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "766"
},
{
"name": "Objective-C",
"bytes": "76300210"
},
{
"name": "Python",
"bytes": "7563"
},
{
"name": "Ruby",
"bytes": "69852"
},
{
"name": "Shell",
"bytes": "4545"
},
{
"name": "Swift",
"bytes": "103066"
}
],
"symlink_target": ""
} |
'use strict';
function Boot() {
}
Boot.prototype = {
preload: function() {
this.load.image('preloader', 'images/preloader.gif');
},
create: function() {
this.game.input.maxPointers = 1;
this.game.state.start('preload');
}
};
module.exports = Boot;
| {
"content_hash": "d6ad686b8ea746a0c55f4993592ad8d3",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 57,
"avg_line_length": 16.9375,
"alnum_prop": 0.6273062730627307,
"repo_name": "bitwater/GoOfLife",
"id": "f2fc6b91dfe4f42056247ed7011975847f31f2f5",
"size": "271",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "flappy-bird/app/scripts/states/boot.js",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "97592"
},
{
"name": "HTML",
"bytes": "280078"
},
{
"name": "JavaScript",
"bytes": "500829"
},
{
"name": "Ruby",
"bytes": "1352"
},
{
"name": "Shell",
"bytes": "473"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PSLAManager
{
class Fact : Table
{
public Fact(String tabName, List<Attribute> tabAttr, List<String> tabListOfSel, Attribute tabPrimaryKey, int tabSize)
: base(tabName, tabAttr, tabListOfSel, tabPrimaryKey, tabSize) {}
public Fact(String tabName, List<Attribute> tabAttr, List<String> tabListOfSel, List<Attribute> tabCompositeKeys, int tabSize)
: base(tabName, tabAttr, tabListOfSel, tabCompositeKeys, tabSize) {}
//if composite key, return the string
public string getCompositeKeys()
{
string stringConcat = String.Empty;
foreach (var v in this.tableCompositeKeys) {
stringConcat += v;
if (v != this.tableCompositeKeys.Last())
stringConcat += ",";
}
return stringConcat;
}
}
}
| {
"content_hash": "1cacf59b48c7f689063de6a580f9f883",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 134,
"avg_line_length": 33.13333333333333,
"alnum_prop": 0.6297786720321932,
"repo_name": "uwdb/PSLAManager",
"id": "a3d32a9b215ab693f09e27d2515c6433e340011e",
"size": "996",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "PSLAManager/Fact.cs",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C#",
"bytes": "46048"
}
],
"symlink_target": ""
} |
package com.blossomproject.core.common.event;
import com.blossomproject.core.common.dto.AbstractDTO;
/**
* Application Event which notify the application when an entity has been created
*
* @param <DTO> the created {@code AbstractDTO}
* @author Maël Gargadennnec
*/
public class CreatedEvent<DTO extends AbstractDTO> extends Event<DTO> {
public CreatedEvent(Object source, DTO dto) {
super(source, dto);
}
}
| {
"content_hash": "1fd7223034bd0adf8a7b78d3aa6351d4",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 81,
"avg_line_length": 25,
"alnum_prop": 0.7458823529411764,
"repo_name": "mgargadennec/blossom",
"id": "4d086afb9317e3fc0c3e5cda49cc6e46d9b81a4e",
"size": "426",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "blossom-core/blossom-core-common/src/main/java/com/blossomproject/core/common/event/CreatedEvent.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "753823"
},
{
"name": "FreeMarker",
"bytes": "235333"
},
{
"name": "Java",
"bytes": "1264060"
},
{
"name": "JavaScript",
"bytes": "1544902"
},
{
"name": "Shell",
"bytes": "636"
}
],
"symlink_target": ""
} |
require 'spec_helper'
RSpec.describe 'Bvnex integration specs' do
let(:client) { Cryptoexchange::Client.new }
let(:market) { 'bvnex' }
let(:ltc_usdt_pair) { Cryptoexchange::Models::MarketPair.new(base: 'ltc', target: 'usdt', market: 'bvnex') }
it 'fetch pairs' do
pairs = client.pairs('bvnex')
expect(pairs).not_to be_empty
pair = pairs.first
expect(pair.base).to_not be nil
expect(pair.target).to_not be nil
expect(pair.market).to eq 'bvnex'
end
it 'give trade url' do
trade_page_url = client.trade_page_url market, base: ltc_usdt_pair.base, target: ltc_usdt_pair.target
expect(trade_page_url).to eq "https://www.bvnex.com/#/trade/ltc_usdt"
end
it 'fetch ticker' do
ticker = client.ticker(ltc_usdt_pair)
expect(ticker.base).to eq 'LTC'
expect(ticker.target).to eq 'USDT'
expect(ticker.market).to eq 'bvnex'
expect(ticker.last).to be_a Numeric
expect(ticker.bid).to be_a Numeric
expect(ticker.ask).to be_a Numeric
expect(ticker.volume).to be_a Numeric
expect(ticker.timestamp).to be nil
expect(ticker.payload).to_not be nil
end
it 'fetch order book' do
order_book = client.order_book(ltc_usdt_pair)
expect(order_book.base).to eq 'LTC'
expect(order_book.target).to eq 'USDT'
expect(order_book.market).to eq 'bvnex'
expect(order_book.asks).to_not be_empty
expect(order_book.bids).to_not be_empty
expect(order_book.asks.first.price).to_not be_nil
expect(order_book.bids.first.amount).to_not be_nil
expect(order_book.bids.first.timestamp).to be_nil
expect(order_book.asks.count).to be > 10
expect(order_book.bids.count).to be > 10
expect(order_book.timestamp).to be_nil
expect(order_book.payload).to_not be nil
end
end
| {
"content_hash": "0b91c22d968988de1c3829c46ae76514",
"timestamp": "",
"source": "github",
"line_count": 55,
"max_line_length": 110,
"avg_line_length": 32.2,
"alnum_prop": 0.6837944664031621,
"repo_name": "coingecko/cryptoexchange",
"id": "37cc0e650eb4703f18a46378474b40e084bab55b",
"size": "1771",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spec/exchanges/bvnex/integration/market_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "3283949"
},
{
"name": "Shell",
"bytes": "131"
}
],
"symlink_target": ""
} |
WIDGET = {type = {}}
-- called by the iupxxx functions
-- obj is a lua table
function WIDGET:Constructor(obj)
-- the parent of the table is the widget class used to create the control
obj.parent = self
-- check the table parameters
self:checkParams(obj)
-- create the IUP control, calling iupCreateXXX
obj.handle = self:CreateIUPelement(obj)
-- set the parameters that are attributes
self:setAttributes(obj)
-- save the table indexed by the handle
iup_handles[obj.handle] = obj
-- the returned value is the handle, not the table
return obj.handle
end
function WIDGET:checkParams (obj)
local type = self.type
local param, func = next(type, nil)
while param do
if not func(obj[param]) then
error("parameter " .. param .. " has wrong value or is not initialized")
end
param, func = next(type, param)
end
end
function WIDGET:setAttributes (obj)
local temp = {}
local f = next(obj, nil)
while f do
temp[f] = 1
f = next(obj, f)
end
f = next(temp, nil)
while f do
obj:set (f, obj[f])
f = next(temp, f)
end
end
function WIDGET:get(index)
if type_string (index) then
if (iup_callbacks[index]) then
return self[index]
else
local INDEX = strupper (index)
local value = IupGetAttribute (self.handle, INDEX)
if value then
local handle = IupGetHandle (value)
if handle then
return handle
else
return value
end
end
end
end
return self[index]
end
function WIDGET:set(index, value)
if type_string (index) then
local INDEX = strupper (index)
local cb = iup_callbacks[index]
-- workaround for resize attribute in dialog
if (index == "resize" and IupGetClassName(self.handle) == "dialog") then
cb = nil
end
if (cb) then
local func = cb[2]
if (not func) then
func = cb[IupGetClassName(self.handle)]
end
iupSetCallback(self.handle, cb[1], func, value)
self[index] = value
return
elseif type_string(value) or type_number(value) then
IupSetAttribute(self.handle, INDEX, value)
return
elseif type_nil(value) then
local old_value = IupGetAttribute(self.handle, INDEX)
if old_value then
IupSetAttribute(self.handle, INDEX, value)
return
end
elseif type_widget(value) then
iupSetName(value)
IupSetAttribute(self.handle, INDEX, value.IUP_name)
return
end
end
self[index] = value
end
function WIDGET:r_destroy()
local i = 1
local elem = self[i]
while elem do
if type_widget (elem) and elem.IUP_parent then
if elem.IUP_parent == self then
elem.IUP_parent = nil
elem:r_destroy ()
else -- wrong parent
error ("Internal table inconsistency")
exit()
end
end
i = i + 1
elem = self[i]
end
iup_handles[self] = nil
end
function WIDGET:destroy()
self:r_destroy ()
IupDestroy (self)
end
function WIDGET:detach()
IupDetach (self)
local parent = self.IUP_parent
if parent then
self.IUP_parent = nil
local i = 1
while parent[i] do
if parent[i] == self then
while parent[i+1] do
parent[i] = parent[i+1]
i = i+1
end
parent[i] = nil
return
end
i = i+1
end
end
end
function WIDGET:append(o)
if IupAppend (self, o) then
o.IUP_parent = self
local i = 1
while self[i] do
if self[i] == o then
return i
end
i = i+1
end
iup_handles[self][i] = o
return i
else
return nil
end
end
function WIDGET:map()
return IupMap(self)
end
function WIDGET:hide()
return IupHide(self)
end
-- ###############
IUPTIMER = {parent = WIDGET}
function IUPTIMER:CreateIUPelement ()
return iupCreateTimer()
end
function iuptimer(o)
return IUPTIMER:Constructor(o)
end
iup.timer = iuptimer
-- ###############
IUPCLIPBOARD = {parent = WIDGET}
function IUPCLIPBOARD:CreateIUPelement ()
return iupCreateClipboard()
end
function iupclipboard(o)
return IUPCLIPBOARD:Constructor(o)
end
iup.clipboard = iupclipboard
-- ###############
IUPDIALOG = {parent = WIDGET, type = {type_widget}}
function IUPDIALOG:CreateIUPelement (obj)
local handle = iupCreateDialog(obj[1])
if (obj[1]) then obj[1].IUP_parent = handle end
return handle
end
function IUPDIALOG:show ()
return IupShow(self)
end
function IUPDIALOG:showxy (x,y)
return IupShowXY(self, x, y)
end
function IUPDIALOG:popup (x, y)
return IupPopup (self, x, y)
end
function iupdialog (o)
return IUPDIALOG:Constructor (o)
end
iup.dialog = iupdialog
-- ###############
IUPRADIO = {parent = WIDGET, type = {type_widget}}
function IUPRADIO:CreateIUPelement (obj)
local handle = iupCreateRadio (obj[1])
if (obj[1]) then obj[1].IUP_parent = handle end
return handle
end
function iupradio (o)
local handle = IUPRADIO:Constructor (o)
iupCreateChildrenNames (handle[1])
return handle
end
iup.radio = iupradio
-- OLD STUFF
function edntoggles (h)
local tmp = {}
local i = 1
while h[i] do
if type_string (h[i]) then
tmp[i] = iuptoggle{title = h[i], action = h.action}
else
error ("option "..i.." must be a string")
end
i = i + 1
end
if h.value then
local j = 1
while h[j] and (h[j] ~= h.value) do
j = j + 1
end
if h[j] then
tmp.value = tmp[j]
end
elseif h.nvalue then
tmp.value = tmp[h.nvalue]
end
return tmp
end
-- OLD STUFF
function edhradio (o)
local toggles = edntoggles (o)
return iupradio{edhbox (toggles); value = toggles.value}
end
-- OLD STUFF
function edvradio (o)
local toggles = edntoggles (o)
return iupradio{edvbox (toggles); value = toggles.value}
end
-- ###############
IUPMENU = {parent = WIDGET}
function IUPMENU:checkParams (obj)
local i = 1
while obj[i] do
local o = obj[i]
if not type_item (o) then -- not a menu item
if type (o) ~= 'table' then
error("parameter " .. i .. " is not a table nor a menu item")
elseif (o[1] and not type_string (o[1])) then
error("parameter " .. i .. " does not have a string title")
elseif (o[2] and not type_string (o[2]) and not type_function (o[2])
and not type_widget (o[2])) then
error("parameter " .. i .. " does not have an action nor a menu")
end
end
i = i + 1
end
end
function IUPMENU:CreateIUPelement (obj)
local handle = iupCreateMenu ()
local i = 1
while obj[i] do
local o = obj[i]
local elem
if type_widget (o) then -- predefined
elem = o
elseif not o[1] then -- Separator
elem = iupseparator {}
elseif type_widget (o[2]) then -- SubMenu
o.title = o[1]
o[1] = o[2]
o[2] = nil
elem = iupsubmenu(o)
else -- Item
o.title = o[1]
o.action = o[2]
o[1] = nil
o[2] = nil
elem = iupitem(o)
end
IupAppend (handle, elem)
elem.IUP_parent = handle
obj[i] = elem
i = i + 1
end
return handle
end
function iupmenu (o)
return IUPMENU:Constructor (o)
end
iup.menu = iupmenu
function IUPMENU:popup (x, y)
return IupPopup (self, x, y)
end
-- ###############
COMPOSITION = {parent = WIDGET}
function COMPOSITION:checkParams (obj)
local i = 1
while obj[i] do
if not type_widget (obj[i]) then
error("parameter " .. i .. " has wrong value or is not initialized")
end
i = i + 1
end
end
function COMPOSITION:CreateIUPelement (obj)
local handle = self:CreateBoxElement ()
local filled = obj.filled
local i = 1
local n = 0
while obj[i] do
n = n + 1
i = i + 1
end
i = 1
if filled == IUP_YES then
obj[i+n] = iupfill{}
IupAppend (handle, obj[i+n])
obj[i+n].IUP_parent = handle
end
while i <= n do
IupAppend (handle, obj[i])
obj[i].IUP_parent = handle
i = i + 1
if filled == IUP_YES then
obj[i+n] = iupfill{}
IupAppend (handle, obj[i+n])
obj[i+n].IUP_parent = handle
end
end
return handle
end
-- ###############
IUPHBOX = {parent = COMPOSITION}
function IUPHBOX:CreateBoxElement ()
return iupCreateHbox ()
end
function iuphbox (o)
return IUPHBOX:Constructor (o)
end
iup.hbox = iuphbox
-- OLD STUFF
function edhbox (o)
o.filled = IUP_YES
return IUPHBOX:Constructor (o)
end
-- OLD STUFF
function edfield (f)
local l, t
if (type_string (f.prompt) or type_number (f.prompt)) then
l = iuplabel {title = f.prompt}
else
error ("parameter prompt has wrong value or is not initialized")
end
if f.value then
t = iuptext {value = f.value}
else
t = iuptext {value = f.nvalue}
end
if t and l then
return edhbox {l, t}
else
return nil
end
end
-- ###############
IUPVBOX = {parent = COMPOSITION}
function IUPVBOX:CreateBoxElement ()
return iupCreateVbox ()
end
function iupvbox (o)
return IUPVBOX:Constructor (o)
end
iup.vbox = iupvbox
-- OLD STUFF
function edvbox (o)
o.filled = IUP_YES
return IUPVBOX:Constructor (o)
end
-- ###############
IUPZBOX = {parent = COMPOSITION}
function IUPZBOX:CreateBoxElement ()
return iupCreateZbox ()
end
function iupzbox (obj)
local handle = IUPZBOX:Constructor (obj)
local i = 1
while obj[i] do
iupSetName(handle[i])
i = i+1
end
return handle
end
iup.zbox = iupzbox
-- ###############
IUPFILL = {parent = WIDGET}
function IUPFILL:CreateIUPelement ()
return iupCreateFill ()
end
function iupfill (o)
return IUPFILL:Constructor (o)
end
iup.fill = iupfill
-- ###############
IUPBUTTON = {parent = WIDGET, type = {title = type_string}}
function IUPBUTTON:CreateIUPelement (obj)
if not obj.title and obj.image then
obj.title=''
end
return iupCreateButton(obj.title)
end
function iupbutton (o)
return IUPBUTTON:Constructor (o)
end
iup.button = iupbutton
-- ###############
IUPTEXT = {parent = WIDGET}
function IUPTEXT:CreateIUPelement ()
return iupCreateText()
end
function iuptext (o)
return IUPTEXT:Constructor (o)
end
iup.text = iuptext
-- ###############
IUPMULTILINE = {parent = IUPTEXT}
function IUPMULTILINE:CreateIUPelement ()
return iupCreateMultiLine()
end
function iupmultiline (o)
return IUPMULTILINE:Constructor (o)
end
iup.multiline = iupmultiline
-- ###############
IUPLABEL = {parent = WIDGET, type = {title = type_string}}
function IUPLABEL:CreateIUPelement (obj)
if not obj.title and obj.image then
obj.title=''
end
return iupCreateLabel (obj.title)
end
function iuplabel (o)
return IUPLABEL:Constructor (o)
end
iup.label = iuplabel
-- ###############
IUPTOGGLE = {parent = IUPBUTTON}
function IUPTOGGLE:CreateIUPelement (obj)
return iupCreateToggle (obj.title)
end
function iuptoggle (o)
return IUPTOGGLE:Constructor (o)
end
iup.toggle = iuptoggle
-- ###############
IUPITEM = {parent = IUPBUTTON}
function IUPITEM:CreateIUPelement (obj)
return iupCreateItem (obj.title)
end
function iupitem (o)
return IUPITEM:Constructor (o)
end
iup.item = iupitem
-- ###############
IUPSUBMENU = {parent = WIDGET, type = {type_menu; title = type_string}}
function IUPSUBMENU:CreateIUPelement (obj)
local h = iupCreateSubmenu (obj.title, obj[1])
obj[1].IUP_parent = h
return h
end
function iupsubmenu (o)
return IUPSUBMENU:Constructor (o)
end
iup.submenu = iupsubmenu
-- ###############
IUPSEPARATOR = {parent = WIDGET}
function IUPSEPARATOR:CreateIUPelement ()
return iupCreateSeparator ()
end
function iupseparator (o)
return IUPSEPARATOR:Constructor (o)
end
iup.separator = iupseparator
-- ###############
IUPFILEDLG = {parent = WIDGET}
function IUPFILEDLG:popup (x, y)
return IupPopup (self, x, y)
end
function IUPFILEDLG:CreateIUPelement ()
return iupCreateFileDlg ()
end
function iupfiledlg (o)
return IUPFILEDLG:Constructor (o)
end
iup.filedlg = iupfiledlg
-- ###############
IUPMESSAGEDLG = {parent = WIDGET}
function IUPMESSAGEDLG:popup (x, y)
return IupPopup (self, x, y)
end
function IUPMESSAGEDLG:CreateIUPelement ()
return iupCreateMessageDlg ()
end
function iupmessagedlg (o)
return IUPMESSAGEDLG:Constructor (o)
end
iup.messagedlg = iupmessagedlg
-- ###############
IUPCOLORDLG = {parent = WIDGET}
function IUPCOLORDLG:popup (x, y)
return IupPopup (self, x, y)
end
function IUPCOLORDLG:CreateIUPelement ()
return iupCreateColorDlg ()
end
function iupcolordlg (o)
return IUPCOLORDLG:Constructor (o)
end
iup.colordlg = iupcolordlg
-- ###############
IUPFONTDLG = {parent = WIDGET}
function IUPFONTDLG:popup (x, y)
return IupPopup (self, x, y)
end
function IUPFONTDLG:CreateIUPelement ()
return iupCreateFontDlg ()
end
function iupfontdlg (o)
return IUPFONTDLG:Constructor (o)
end
iup.fontdlg = iupfontdlg
-- ###############
IUPUSER = {parent = WIDGET}
function IUPUSER:CreateIUPelement ()
return iupCreateUser ()
end
function iupuser ()
return IUPUSER:Constructor ()
end
iup.user = iupuser
-- ###############
IUPNORMALIZER = {parent = WIDGET}
function IUPNORMALIZER:checkParams (obj)
local i = 1
while obj[i] do
if not type_widget (obj[i]) then
error("parameter " .. i .. " has wrong value or is not initialized")
end
i = i + 1
end
end
function IUPNORMALIZER:CreateIUPelement (obj)
local handle = iupCreateNormalizer ()
local i = 1
while obj[i] do
handle.addcontrol = obj[i]
i = i + 1
end
return handle
end
function iupnormalizer ()
return IUPNORMALIZER:Constructor ()
end
iup.normalizer = iupnormalizer
-- ###############
IUPFRAME = {parent = WIDGET, type = {type_widget}}
function IUPFRAME:CreateIUPelement (obj)
local h = iupCreateFrame (obj[1])
if (obj[1]) then obj[1].IUP_parent = h end
return h
end
function iupframe (o)
return IUPFRAME:Constructor (o)
end
iup.frame = iupframe
-- ###############
IUPCANVAS = {parent = WIDGET}
function IUPCANVAS:CreateIUPelement ()
return iupCreateCanvas ()
end
function iupcanvas (o)
return IUPCANVAS:Constructor (o)
end
iup.canvas = iupcanvas
-- ###############
IUPLIST = {parent = WIDGET}
function IUPLIST:CreateIUPelement ()
return iupCreateList ()
end
function IUPLIST:get(index)
if type (index) == 'number' then
return IupGetAttribute (self.handle, ""..index)
else
return WIDGET.get(self, index)
end
end
function IUPLIST:set (index, value)
if type (index) == 'number' then
if (type_string (value) or type_number (value)) then
return IupSetAttribute (self.handle, ""..index, ""..value)
elseif value == nil then
return IupSetAttribute (self.handle, ""..index, value)
end
end
return WIDGET.set(self, index, value)
end
function iuplist (o)
return IUPLIST:Constructor (o)
end
iup.list = iuplist
-- ###############
IUPIMAGE = {parent = WIDGET}
function IUPIMAGE:checkParams (obj)
local i = 1
while obj[i] do
local j = 1
while obj[i][j] do
if type (obj[i][j]) ~= 'number' then
error ("non-numeric value in image definition")
end
j = j + 1
end
if obj.width and (j - 1) ~= obj.width then
error ("inconsistent image lenght")
else
obj.width = j - 1
end
i = i + 1
end
obj.height = i - 1
end
function IUPIMAGE:CreateIUPelement (obj)
local handle = iupCreateImage (obj.width, obj.height, obj)
if type (obj.colors) == 'table' then
local i = 1
while obj.colors[i] do
IupSetAttribute (handle, i, obj.colors[i])
i = i + 1
end
end
return handle
end
function iupimage (o)
return IUPIMAGE:Constructor (o)
end
iup.image = iupimage
IUPIMAGERGB = {parent = WIDGET}
function IUPIMAGERGB:CreateIUPelement (obj)
return iupCreateImageRGB(obj.width, obj.height, obj.pixels)
end
function iupimagergb (o)
return IUPIMAGERGB:Constructor (o)
end
iup.imagergb = iupimagergb
IUPIMAGERGBA = {parent = WIDGET}
function IUPIMAGERGBA:CreateIUPelement (obj)
return iupCreateImageRGBA(obj.width, obj.height, obj.pixels)
end
function iupimagergba (o)
return IUPIMAGERGBA:Constructor (o)
end
iup.imagergba = iupimagergba
-- ###############
IUPPROGRESSBAR = {parent = WIDGET}
function IUPPROGRESSBAR:CreateIUPelement ()
return iupCreateProgressBar()
end
function iupprogressbar (o)
return IUPPROGRESSBAR:Constructor (o)
end
iup.progressbar = iupprogressbar
-- #################################################################################
-- Callbacks
-- #################################################################################
-- global list of callbacks
-- index is the Lua callback name
-- each callback contains the full name, and the C callback
iup_callbacks =
{
action = {"ACTION", nil},
actioncb = {"ACTION_CB", nil},
getfocus = {"GETFOCUS_CB", iup_getfocus_cb},
killfocus = {"KILLFOCUS_CB", iup_killfocus_cb},
focus = {"FOCUS_CB", iup_focus_cb},
k_any = {"K_ANY", iup_k_any},
help = {"HELP_CB", iup_help_cb},
caretcb = {"CARET_CB", iup_caret_cb},
keypress = {"KEYPRESS_CB", iup_keypress_cb},
scroll = {"SCROLL_CB", iup_scroll_cb},
trayclick = {"TRAYCLICK_CB", iup_trayclick_cb},
close = {"CLOSE_CB", iup_close_cb},
copydata = {"COPYDATA_CB", iup_copydata_cb},
open = {"OPEN_CB", iup_open_cb},
showcb = {"SHOW_CB", iup_show_cb},
mapcb = {"MAP_CB", iup_map_cb},
unmapcb = {"UNMAP_CB", iup_unmap_cb},
destroycb = {"DESTROY_CB", iup_destroy_cb},
dropfiles = {"DROPFILES_CB", iup_dropfiles_cb},
menuclose = {"MENUCLOSE_CB", iup_menuclose_cb},
highlight = {"HIGHLIGHT_CB", iup_highlight_cb},
wom = {"WOM_CB", iup_wom_cb},
wheel = {"WHEEL_CB", iup_wheel_cb},
button = {"BUTTON_CB", iup_button_cb},
resize = {"RESIZE_CB", iup_resize_cb},
move = {"RESIZE_CB", iup_move_cb},
motion = {"MOTION_CB", iup_motion_cb},
enterwindow = {"ENTERWINDOW_CB", iup_enterwindow_cb},
leavewindow = {"LEAVEWINDOW_CB", iup_leavewindow_cb},
edit = {"EDIT_CB", iup_edit_cb},
multiselect = {"MULTISELECT_CB", iup_multiselect_cb},
filecb = {"FILE_CB", iup_file_cb},
mdiactivatecb = {"MDIACTIVATE_CB", iup_mdiactivate_cb},
dropdowncb = {"DROPDOWN_CB", iup_dropdown_cb},
dblclickcb = {"DBLCLICK_CB", iup_dblclick_cb},
}
iup_callbacks.action.toggle = iup_action_toggle
iup_callbacks.action.multiline = iup_action_text
iup_callbacks.action.text = iup_action_text
iup_callbacks.action.button = iup_action_button
iup_callbacks.action.list = iup_action_list
iup_callbacks.action.item = iup_action_button
iup_callbacks.action.canvas = iup_action_canvas
-- must set here because it is also used elsewhere with a different signature
iup_callbacks.actioncb.timer = iup_action_timer
-- aliases for the full names
iup_callbacks.action_cb = iup_callbacks.actioncb
iup_callbacks.getfocus_cb = iup_callbacks.getfocus
iup_callbacks.killfocus_cb = iup_callbacks.killfocus
iup_callbacks.focus_cb = iup_callbacks.focus
iup_callbacks.k_any = iup_callbacks.k_any
iup_callbacks.help_cb = iup_callbacks.help
iup_callbacks.caret_cb = iup_callbacks.caretcb
iup_callbacks.keypress_cb = iup_callbacks.keypress
iup_callbacks.scroll_cb = iup_callbacks.scroll
iup_callbacks.trayclick_cb = iup_callbacks.trayclick
iup_callbacks.close_cb = iup_callbacks.close
iup_callbacks.copydata_cb = iup_callbacks.copydata
iup_callbacks.open_cb = iup_callbacks.open
iup_callbacks.show_cb = iup_callbacks.showcb
iup_callbacks.map_cb = iup_callbacks.mapcb
iup_callbacks.unmap_cb = iup_callbacks.unmapcb
iup_callbacks.destroy_cb = iup_callbacks.destroycb
iup_callbacks.dropfiles_cb = iup_callbacks.dropfiles
iup_callbacks.menuclose_cb = iup_callbacks.menuclose
iup_callbacks.highlight_cb = iup_callbacks.highlight
iup_callbacks.wom_cb = iup_callbacks.wom
iup_callbacks.wheel_cb = iup_callbacks.wheel
iup_callbacks.button_cb = iup_callbacks.button
iup_callbacks.resize_cb = iup_callbacks.resize
iup_callbacks.move_cb = iup_callbacks.move
iup_callbacks.motion_cb = iup_callbacks.motion
iup_callbacks.enterwindow_cb = iup_callbacks.enterwindow
iup_callbacks.leavewindow_cb = iup_callbacks.leavewindow
iup_callbacks.edit_cb = iup_callbacks.edit
iup_callbacks.multiselect_cb = iup_callbacks.multiselect
iup_callbacks.mdiactivate_cb = iup_callbacks.mdiactivatecb
iup_callbacks.file_cb = iup_callbacks.filecb
iup_callbacks.dropdown_cb = iup_callbacks.dropdowncb
iup_callbacks.dblclick_cb = iup_callbacks.dblclickcb
iup_callbacks.valuechanged_cb = iup_callbacks.valuechangedcb
| {
"content_hash": "03d50b9471a4a6fef59c8fc1d6053972",
"timestamp": "",
"source": "github",
"line_count": 939,
"max_line_length": 84,
"avg_line_length": 22.171458998935037,
"alnum_prop": 0.641481339161343,
"repo_name": "sanikoyes/iup",
"id": "76b2faf25e05e02c51d3e07a14a00e019ec21d7a",
"size": "21109",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "srclua3/iuplua_widgets.lua",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "34"
},
{
"name": "Batchfile",
"bytes": "10717"
},
{
"name": "C",
"bytes": "9868012"
},
{
"name": "C++",
"bytes": "6978963"
},
{
"name": "CSS",
"bytes": "14107"
},
{
"name": "HTML",
"bytes": "2240422"
},
{
"name": "Lua",
"bytes": "682394"
},
{
"name": "Makefile",
"bytes": "139721"
},
{
"name": "Shell",
"bytes": "12420"
}
],
"symlink_target": ""
} |
name 'jenkins_plugins_workflow'
depends 'jenkins'
depends 'jenkins_plugins'
| {
"content_hash": "84108357f07019fbb58d148dd7bed957",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 31,
"avg_line_length": 25.333333333333332,
"alnum_prop": 0.8026315789473685,
"repo_name": "monkeylittleinc/jenkins_plugins",
"id": "ceb752ad8e751fe502e6d9035a69676ef6b46a47",
"size": "76",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/fixtures/cookbooks/jenkins_plugins_workflow/metadata.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "2236"
},
{
"name": "Ruby",
"bytes": "36857"
}
],
"symlink_target": ""
} |
namespace mojo {
namespace {
const int kMaxExpectedResponseLength = 2048;
NetAddressPtr GetLocalHostWithAnyPort() {
NetAddressPtr addr(NetAddress::New());
addr->family = NetAddressFamily::IPV4;
addr->ipv4 = NetAddressIPv4::New();
addr->ipv4->port = 0;
addr->ipv4->addr.resize(4);
addr->ipv4->addr[0] = 127;
addr->ipv4->addr[1] = 0;
addr->ipv4->addr[2] = 0;
addr->ipv4->addr[3] = 1;
return addr;
}
using TestHeaders = std::vector<std::pair<std::string, std::string>>;
struct TestRequest {
std::string method;
std::string url;
TestHeaders headers;
scoped_ptr<std::string> body;
};
struct TestResponse {
uint32_t status_code;
TestHeaders headers;
scoped_ptr<std::string> body;
};
std::string MakeRequestMessage(const TestRequest& data) {
std::string message = data.method + " " + data.url + " HTTP/1.1\r\n";
for (const auto& item : data.headers)
message += item.first + ": " + item.second + "\r\n";
message += "\r\n";
if (data.body)
message += *data.body;
return message;
}
HttpResponsePtr MakeResponseStruct(const TestResponse& data) {
HttpResponsePtr response(HttpResponse::New());
response->status_code = data.status_code;
response->headers.resize(data.headers.size());
size_t index = 0;
for (const auto& item : data.headers) {
HttpHeaderPtr header(HttpHeader::New());
header->name = item.first;
header->value = item.second;
response->headers[index++] = std::move(header);
}
if (data.body) {
uint32_t num_bytes = static_cast<uint32_t>(data.body->size());
MojoCreateDataPipeOptions options;
options.struct_size = sizeof(MojoCreateDataPipeOptions);
options.flags = MOJO_CREATE_DATA_PIPE_OPTIONS_FLAG_NONE;
options.element_num_bytes = 1;
options.capacity_num_bytes = num_bytes;
DataPipe data_pipe(options);
response->body = std::move(data_pipe.consumer_handle);
MojoResult result =
WriteDataRaw(data_pipe.producer_handle.get(), data.body->data(),
&num_bytes, MOJO_WRITE_DATA_FLAG_ALL_OR_NONE);
EXPECT_EQ(MOJO_RESULT_OK, result);
}
return response;
}
void CheckHeaders(const TestHeaders& expected,
const Array<HttpHeaderPtr>& headers) {
// The server impl fiddles with Content-Length and Content-Type. So we don't
// do a strict check here.
std::map<std::string, std::string> header_map;
for (size_t i = 0; i < headers.size(); ++i) {
std::string lower_name =
base::ToLowerASCII(headers[i]->name.To<std::string>());
header_map[lower_name] = headers[i]->value;
}
for (const auto& item : expected) {
std::string lower_name = base::ToLowerASCII(item.first);
EXPECT_NE(header_map.end(), header_map.find(lower_name));
EXPECT_EQ(item.second, header_map[lower_name]);
}
}
void CheckRequest(const TestRequest& expected, HttpRequestPtr request) {
EXPECT_EQ(expected.method, request->method);
EXPECT_EQ(expected.url, request->url);
CheckHeaders(expected.headers, request->headers);
if (expected.body) {
EXPECT_TRUE(request->body.is_valid());
std::string body;
common::BlockingCopyToString(std::move(request->body), &body);
EXPECT_EQ(*expected.body, body);
} else {
EXPECT_FALSE(request->body.is_valid());
}
}
void CheckResponse(const TestResponse& expected, const std::string& response) {
int header_end =
net::HttpUtil::LocateEndOfHeaders(response.c_str(), response.size());
std::string assembled_headers =
net::HttpUtil::AssembleRawHeaders(response.c_str(), header_end);
scoped_refptr<net::HttpResponseHeaders> parsed_headers(
new net::HttpResponseHeaders(assembled_headers));
EXPECT_EQ(expected.status_code,
static_cast<uint32_t>(parsed_headers->response_code()));
for (const auto& item : expected.headers)
EXPECT_TRUE(parsed_headers->HasHeaderValue(item.first, item.second));
if (expected.body) {
EXPECT_NE(-1, header_end);
std::string body(response, static_cast<size_t>(header_end));
EXPECT_EQ(*expected.body, body);
} else {
EXPECT_EQ(response.size(), static_cast<size_t>(header_end));
}
}
class TestHttpClient {
public:
TestHttpClient() : connect_result_(net::OK) {}
void Connect(const net::IPEndPoint& address) {
net::AddressList addresses(address);
net::NetLog::Source source;
socket_.reset(new net::TCPClientSocket(addresses, NULL, source));
base::RunLoop run_loop;
connect_result_ = socket_->Connect(base::Bind(&TestHttpClient::OnConnect,
base::Unretained(this),
run_loop.QuitClosure()));
if (connect_result_ == net::ERR_IO_PENDING)
run_loop.Run();
ASSERT_EQ(net::OK, connect_result_);
}
void Send(const std::string& data) {
write_buffer_ = new net::DrainableIOBuffer(new net::StringIOBuffer(data),
data.length());
Write();
}
// Note: This method determines the end of the response only by Content-Length
// and connection termination. Besides, it doesn't truncate at the end of the
// response, so |message| may return more data (e.g., part of the next
// response).
void ReadResponse(std::string* message) {
if (!Read(message, 1))
return;
while (!IsCompleteResponse(*message)) {
std::string chunk;
if (!Read(&chunk, 1))
return;
message->append(chunk);
}
return;
}
private:
void OnConnect(const base::Closure& quit_loop, int result) {
connect_result_ = result;
quit_loop.Run();
}
void Write() {
int result = socket_->Write(
write_buffer_.get(), write_buffer_->BytesRemaining(),
base::Bind(&TestHttpClient::OnWrite, base::Unretained(this)));
if (result != net::ERR_IO_PENDING)
OnWrite(result);
}
void OnWrite(int result) {
ASSERT_GT(result, 0);
write_buffer_->DidConsume(result);
if (write_buffer_->BytesRemaining())
Write();
}
bool Read(std::string* message, int expected_bytes) {
int total_bytes_received = 0;
message->clear();
while (total_bytes_received < expected_bytes) {
net::TestCompletionCallback callback;
ReadInternal(callback.callback());
int bytes_received = callback.WaitForResult();
if (bytes_received <= 0)
return false;
total_bytes_received += bytes_received;
message->append(read_buffer_->data(), bytes_received);
}
return true;
}
void ReadInternal(const net::CompletionCallback& callback) {
read_buffer_ = new net::IOBufferWithSize(kMaxExpectedResponseLength);
int result =
socket_->Read(read_buffer_.get(), kMaxExpectedResponseLength, callback);
if (result != net::ERR_IO_PENDING)
callback.Run(result);
}
bool IsCompleteResponse(const std::string& response) {
// Check end of headers first.
int end_of_headers =
net::HttpUtil::LocateEndOfHeaders(response.data(), response.size());
if (end_of_headers < 0)
return false;
// Return true if response has data equal to or more than content length.
int64_t body_size = static_cast<int64_t>(response.size()) - end_of_headers;
DCHECK_LE(0, body_size);
scoped_refptr<net::HttpResponseHeaders> headers(
new net::HttpResponseHeaders(net::HttpUtil::AssembleRawHeaders(
response.data(), end_of_headers)));
return body_size >= headers->GetContentLength();
}
scoped_refptr<net::IOBufferWithSize> read_buffer_;
scoped_refptr<net::DrainableIOBuffer> write_buffer_;
scoped_ptr<net::TCPClientSocket> socket_;
int connect_result_;
DISALLOW_COPY_AND_ASSIGN(TestHttpClient);
};
class WebSocketClientImpl : public WebSocketClient {
public:
explicit WebSocketClientImpl()
: binding_(this, &client_ptr_),
wait_for_message_count_(0),
run_loop_(nullptr) {}
~WebSocketClientImpl() override {}
// Establishes a connection from the client side.
void Connect(WebSocketPtr web_socket, const std::string& url) {
web_socket_ = std::move(web_socket);
DataPipe data_pipe;
send_stream_ = std::move(data_pipe.producer_handle);
write_send_stream_.reset(new WebSocketWriteQueue(send_stream_.get()));
web_socket_->Connect(url, Array<String>(), "http://example.com",
std::move(data_pipe.consumer_handle),
std::move(client_ptr_));
}
// Establishes a connection from the server side.
void AcceptConnectRequest(
const HttpConnectionDelegate::OnReceivedWebSocketRequestCallback&
callback) {
InterfaceRequest<WebSocket> web_socket_request = GetProxy(&web_socket_);
DataPipe data_pipe;
send_stream_ = std::move(data_pipe.producer_handle);
write_send_stream_.reset(new WebSocketWriteQueue(send_stream_.get()));
callback.Run(std::move(web_socket_request),
std::move(data_pipe.consumer_handle), std::move(client_ptr_));
}
void WaitForConnectCompletion() {
DCHECK(!run_loop_);
if (receive_stream_.is_valid())
return;
base::RunLoop run_loop;
run_loop_ = &run_loop;
run_loop.Run();
run_loop_ = nullptr;
}
void Send(const std::string& message) {
DCHECK(!message.empty());
uint32_t size = static_cast<uint32_t>(message.size());
write_send_stream_->Write(
&message[0], size,
base::Bind(&WebSocketClientImpl::OnFinishedWritingSendStream,
base::Unretained(this), size));
}
void WaitForMessage(size_t count) {
DCHECK(!run_loop_);
if (received_messages_.size() >= count)
return;
wait_for_message_count_ = count;
base::RunLoop run_loop;
run_loop_ = &run_loop;
run_loop.Run();
run_loop_ = nullptr;
}
std::vector<std::string>& received_messages() { return received_messages_; }
private:
// WebSocketClient implementation.
void DidConnect(const String& selected_subprotocol,
const String& extensions,
ScopedDataPipeConsumerHandle receive_stream) override {
receive_stream_ = std::move(receive_stream);
read_receive_stream_.reset(new WebSocketReadQueue(receive_stream_.get()));
web_socket_->FlowControl(2048);
if (run_loop_)
run_loop_->Quit();
}
void DidReceiveData(bool fin,
WebSocket::MessageType type,
uint32_t num_bytes) override {
DCHECK(num_bytes > 0);
read_receive_stream_->Read(
num_bytes,
base::Bind(&WebSocketClientImpl::OnFinishedReadingReceiveStream,
base::Unretained(this), num_bytes));
}
void DidReceiveFlowControl(int64_t quota) override {}
void DidFail(const String& message) override {}
void DidClose(bool was_clean, uint16_t code, const String& reason) override {}
void OnFinishedWritingSendStream(uint32_t num_bytes, const char* buffer) {
EXPECT_TRUE(buffer);
web_socket_->Send(true, WebSocket::MessageType::TEXT, num_bytes);
}
void OnFinishedReadingReceiveStream(uint32_t num_bytes, const char* data) {
EXPECT_TRUE(data);
received_messages_.push_back(std::string(data, num_bytes));
if (run_loop_ && received_messages_.size() >= wait_for_message_count_) {
wait_for_message_count_ = 0;
run_loop_->Quit();
}
}
WebSocketClientPtr client_ptr_;
Binding<WebSocketClient> binding_;
WebSocketPtr web_socket_;
ScopedDataPipeProducerHandle send_stream_;
scoped_ptr<WebSocketWriteQueue> write_send_stream_;
ScopedDataPipeConsumerHandle receive_stream_;
scoped_ptr<WebSocketReadQueue> read_receive_stream_;
std::vector<std::string> received_messages_;
size_t wait_for_message_count_;
// Pointing to a stack-allocated RunLoop instance.
base::RunLoop* run_loop_;
DISALLOW_COPY_AND_ASSIGN(WebSocketClientImpl);
};
class HttpConnectionDelegateImpl : public HttpConnectionDelegate {
public:
struct PendingRequest {
HttpRequestPtr request;
OnReceivedRequestCallback callback;
};
HttpConnectionDelegateImpl(HttpConnectionPtr connection,
InterfaceRequest<HttpConnectionDelegate> request)
: connection_(std::move(connection)),
binding_(this, std::move(request)),
wait_for_request_count_(0),
run_loop_(nullptr) {}
~HttpConnectionDelegateImpl() override {}
// HttpConnectionDelegate implementation:
void OnReceivedRequest(HttpRequestPtr request,
const OnReceivedRequestCallback& callback) override {
linked_ptr<PendingRequest> pending_request(new PendingRequest);
pending_request->request = std::move(request);
pending_request->callback = callback;
pending_requests_.push_back(pending_request);
if (run_loop_ && pending_requests_.size() >= wait_for_request_count_) {
wait_for_request_count_ = 0;
run_loop_->Quit();
}
}
void OnReceivedWebSocketRequest(
HttpRequestPtr request,
const OnReceivedWebSocketRequestCallback& callback) override {
web_socket_.reset(new WebSocketClientImpl());
web_socket_->AcceptConnectRequest(callback);
if (run_loop_)
run_loop_->Quit();
}
void SendResponse(HttpResponsePtr response) {
ASSERT_FALSE(pending_requests_.empty());
linked_ptr<PendingRequest> request = pending_requests_[0];
pending_requests_.erase(pending_requests_.begin());
request->callback.Run(std::move(response));
}
void WaitForRequest(size_t count) {
DCHECK(!run_loop_);
if (pending_requests_.size() >= count)
return;
wait_for_request_count_ = count;
base::RunLoop run_loop;
run_loop_ = &run_loop;
run_loop.Run();
run_loop_ = nullptr;
}
void WaitForWebSocketRequest() {
DCHECK(!run_loop_);
if (web_socket_)
return;
base::RunLoop run_loop;
run_loop_ = &run_loop;
run_loop.Run();
run_loop_ = nullptr;
}
std::vector<linked_ptr<PendingRequest>>& pending_requests() {
return pending_requests_;
}
WebSocketClientImpl* web_socket() { return web_socket_.get(); }
private:
HttpConnectionPtr connection_;
Binding<HttpConnectionDelegate> binding_;
std::vector<linked_ptr<PendingRequest>> pending_requests_;
size_t wait_for_request_count_;
scoped_ptr<WebSocketClientImpl> web_socket_;
// Pointing to a stack-allocated RunLoop instance.
base::RunLoop* run_loop_;
DISALLOW_COPY_AND_ASSIGN(HttpConnectionDelegateImpl);
};
class HttpServerDelegateImpl : public HttpServerDelegate {
public:
explicit HttpServerDelegateImpl(HttpServerDelegatePtr* delegate_ptr)
: binding_(this, delegate_ptr),
wait_for_connection_count_(0),
run_loop_(nullptr) {}
~HttpServerDelegateImpl() override {}
// HttpServerDelegate implementation.
void OnConnected(HttpConnectionPtr connection,
InterfaceRequest<HttpConnectionDelegate> delegate) override {
connections_.push_back(make_linked_ptr(new HttpConnectionDelegateImpl(
std::move(connection), std::move(delegate))));
if (run_loop_ && connections_.size() >= wait_for_connection_count_) {
wait_for_connection_count_ = 0;
run_loop_->Quit();
}
}
void WaitForConnection(size_t count) {
DCHECK(!run_loop_);
if (connections_.size() >= count)
return;
wait_for_connection_count_ = count;
base::RunLoop run_loop;
run_loop_ = &run_loop;
run_loop.Run();
run_loop_ = nullptr;
}
std::vector<linked_ptr<HttpConnectionDelegateImpl>>& connections() {
return connections_;
}
private:
Binding<HttpServerDelegate> binding_;
std::vector<linked_ptr<HttpConnectionDelegateImpl>> connections_;
size_t wait_for_connection_count_;
// Pointing to a stack-allocated RunLoop instance.
base::RunLoop* run_loop_;
DISALLOW_COPY_AND_ASSIGN(HttpServerDelegateImpl);
};
class HttpServerTest : public test::ShellTest {
public:
HttpServerTest()
: ShellTest("exe:network_service_unittests") {}
~HttpServerTest() override {}
protected:
void SetUp() override {
ShellTest::SetUp();
scoped_ptr<Connection> connection =
connector()->Connect("mojo:network_service");
connection->GetInterface(&network_service_);
connection->GetInterface(&web_socket_factory_);
}
scoped_ptr<base::MessageLoop> CreateMessageLoop() override {
return make_scoped_ptr(new base::MessageLoop(base::MessageLoop::TYPE_IO));
}
void CreateHttpServer(HttpServerDelegatePtr delegate,
NetAddressPtr* out_bound_to) {
base::RunLoop loop;
network_service_->CreateHttpServer(
GetLocalHostWithAnyPort(), std::move(delegate),
[out_bound_to, &loop](NetworkErrorPtr result, NetAddressPtr bound_to) {
ASSERT_EQ(net::OK, result->code);
EXPECT_NE(0u, bound_to->ipv4->port);
*out_bound_to = std::move(bound_to);
loop.Quit();
});
loop.Run();
}
NetworkServicePtr network_service_;
WebSocketFactoryPtr web_socket_factory_;
private:
DISALLOW_COPY_AND_ASSIGN(HttpServerTest);
};
} // namespace
TEST_F(HttpServerTest, BasicHttpRequestResponse) {
NetAddressPtr bound_to;
HttpServerDelegatePtr server_delegate_ptr;
HttpServerDelegateImpl server_delegate_impl(&server_delegate_ptr);
CreateHttpServer(std::move(server_delegate_ptr), &bound_to);
TestHttpClient client;
client.Connect(bound_to.To<net::IPEndPoint>());
server_delegate_impl.WaitForConnection(1);
HttpConnectionDelegateImpl& connection =
*server_delegate_impl.connections()[0];
TestRequest request_data = {"HEAD", "/test", {{"Hello", "World"}}, nullptr};
client.Send(MakeRequestMessage(request_data));
connection.WaitForRequest(1);
CheckRequest(request_data,
std::move(connection.pending_requests()[0]->request));
TestResponse response_data = {200, {{"Content-Length", "4"}}, nullptr};
connection.SendResponse(MakeResponseStruct(response_data));
// This causes the underlying TCP connection to be closed. The client can
// determine the end of the response based on that.
server_delegate_impl.connections().clear();
std::string response_message;
client.ReadResponse(&response_message);
CheckResponse(response_data, response_message);
}
TEST_F(HttpServerTest, HttpRequestResponseWithBody) {
NetAddressPtr bound_to;
HttpServerDelegatePtr server_delegate_ptr;
HttpServerDelegateImpl server_delegate_impl(&server_delegate_ptr);
CreateHttpServer(std::move(server_delegate_ptr), &bound_to);
TestHttpClient client;
client.Connect(bound_to.To<net::IPEndPoint>());
server_delegate_impl.WaitForConnection(1);
HttpConnectionDelegateImpl& connection =
*server_delegate_impl.connections()[0];
TestRequest request_data = {
"Post",
"/test",
{{"Hello", "World"},
{"Content-Length", "23"},
{"Content-Type", "text/plain"}},
make_scoped_ptr(new std::string("This is a test request!"))};
client.Send(MakeRequestMessage(request_data));
connection.WaitForRequest(1);
CheckRequest(request_data,
std::move(connection.pending_requests()[0]->request));
TestResponse response_data = {
200,
{{"Content-Length", "26"}},
make_scoped_ptr(new std::string("This is a test response..."))};
connection.SendResponse(MakeResponseStruct(response_data));
std::string response_message;
client.ReadResponse(&response_message);
CheckResponse(response_data, response_message);
}
TEST_F(HttpServerTest, WebSocket) {
NetAddressPtr bound_to;
HttpServerDelegatePtr server_delegate_ptr;
HttpServerDelegateImpl server_delegate_impl(&server_delegate_ptr);
CreateHttpServer(std::move(server_delegate_ptr), &bound_to);
WebSocketPtr web_socket_ptr;
web_socket_factory_->CreateWebSocket(GetProxy(&web_socket_ptr));
WebSocketClientImpl socket_0;
socket_0.Connect(
std::move(web_socket_ptr),
base::StringPrintf("ws://127.0.0.1:%d/hello", bound_to->ipv4->port));
server_delegate_impl.WaitForConnection(1);
HttpConnectionDelegateImpl& connection =
*server_delegate_impl.connections()[0];
connection.WaitForWebSocketRequest();
WebSocketClientImpl& socket_1 = *connection.web_socket();
socket_1.WaitForConnectCompletion();
socket_0.WaitForConnectCompletion();
socket_0.Send("Hello");
socket_0.Send("world!");
socket_1.WaitForMessage(2);
EXPECT_EQ("Hello", socket_1.received_messages()[0]);
EXPECT_EQ("world!", socket_1.received_messages()[1]);
socket_1.Send("How do");
socket_1.Send("you do?");
socket_0.WaitForMessage(2);
EXPECT_EQ("How do", socket_0.received_messages()[0]);
EXPECT_EQ("you do?", socket_0.received_messages()[1]);
}
} // namespace mojo
| {
"content_hash": "cad0144cdd0f53e04de08b5068dcfa27",
"timestamp": "",
"source": "github",
"line_count": 664,
"max_line_length": 80,
"avg_line_length": 31.121987951807228,
"alnum_prop": 0.6721993709170094,
"repo_name": "junhuac/MQUIC",
"id": "dc9769b727f9bf7e731de809d043baf0f783e26a",
"size": "22233",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/mojo/services/network/http_server_unittest.cc",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "25707"
},
{
"name": "Assembly",
"bytes": "5386"
},
{
"name": "Batchfile",
"bytes": "42909"
},
{
"name": "C",
"bytes": "1168925"
},
{
"name": "C#",
"bytes": "81308"
},
{
"name": "C++",
"bytes": "43919800"
},
{
"name": "CMake",
"bytes": "46379"
},
{
"name": "CSS",
"bytes": "19668"
},
{
"name": "Emacs Lisp",
"bytes": "32613"
},
{
"name": "Go",
"bytes": "7247"
},
{
"name": "Groff",
"bytes": "127224"
},
{
"name": "HTML",
"bytes": "2548385"
},
{
"name": "Java",
"bytes": "1332462"
},
{
"name": "JavaScript",
"bytes": "851006"
},
{
"name": "M4",
"bytes": "29823"
},
{
"name": "Makefile",
"bytes": "459525"
},
{
"name": "Objective-C",
"bytes": "120158"
},
{
"name": "Objective-C++",
"bytes": "330017"
},
{
"name": "PHP",
"bytes": "11283"
},
{
"name": "Protocol Buffer",
"bytes": "2991"
},
{
"name": "Python",
"bytes": "16872234"
},
{
"name": "R",
"bytes": "1842"
},
{
"name": "Ruby",
"bytes": "937"
},
{
"name": "Shell",
"bytes": "764509"
},
{
"name": "Swift",
"bytes": "116"
},
{
"name": "VimL",
"bytes": "12288"
},
{
"name": "nesC",
"bytes": "14779"
}
],
"symlink_target": ""
} |
package iso20022
// Choice of format for the allegement status.
type AllegementStatus4Choice struct {
// Status of the allegement reported.
Code *AllegementStatus1Code `xml:"Cd"`
// Status of the allegement reported.
Proprietary *GenericIdentification47 `xml:"Prtry"`
}
func (a *AllegementStatus4Choice) SetCode(value string) {
a.Code = (*AllegementStatus1Code)(&value)
}
func (a *AllegementStatus4Choice) AddProprietary() *GenericIdentification47 {
a.Proprietary = new(GenericIdentification47)
return a.Proprietary
}
| {
"content_hash": "c522e039cce9489001d5790e2fed7d7f",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 77,
"avg_line_length": 26.5,
"alnum_prop": 0.7773584905660378,
"repo_name": "fgrid/iso20022",
"id": "f3d51d64c76741ef703f09e7bfd79e9434c7effe",
"size": "530",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "AllegementStatus4Choice.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Go",
"bytes": "21383920"
}
],
"symlink_target": ""
} |
package com.facebook.buck.rules.modern.config;
import com.facebook.buck.core.config.BuckConfig;
import com.facebook.buck.core.exceptions.HumanReadableException;
import java.util.function.Supplier;
/** Parses the values of a buckconfig section into a {@link ModernBuildRuleStrategyConfig}. */
public class ModernBuildRuleStrategyConfigFromSection implements ModernBuildRuleStrategyConfig {
private final BuckConfig delegate;
private final String section;
public ModernBuildRuleStrategyConfigFromSection(BuckConfig delegate, String section) {
this.delegate = delegate;
this.section = section;
}
@Override
public ModernBuildRuleBuildStrategy getBuildStrategy() {
return delegate
.getEnum(section, "strategy", ModernBuildRuleBuildStrategy.class)
.orElse(ModernBuildRuleBuildStrategy.DEFAULT);
}
@Override
public HybridLocalBuildStrategyConfig getHybridLocalConfig() {
int localJobs = delegate.getInteger(section, "local_jobs").orElseThrow(requires("local_jobs"));
int remoteJobs =
delegate.getInteger(section, "delegate_jobs").orElseThrow(requires("delegate_jobs"));
String delegateFlavor =
delegate.getValue(section, "delegate").orElseThrow(requires("delegate"));
ModernBuildRuleStrategyConfig delegate = getFlavoredStrategyConfig(delegateFlavor);
return new HybridLocalBuildStrategyConfig(localJobs, remoteJobs, delegate);
}
private Supplier<HumanReadableException> requires(String key) {
return () ->
new HumanReadableException(
"hybrid_local strategy requires %s configuration (in %s section).", key, section);
}
public ModernBuildRuleStrategyConfig getFlavoredStrategyConfig(String flavor) {
return new ModernBuildRuleStrategyConfigFromSection(
delegate, String.format("%s#%s", ModernBuildRuleConfig.SECTION, flavor));
}
}
| {
"content_hash": "ef566314d17310a1ff35908b7c7075b5",
"timestamp": "",
"source": "github",
"line_count": 47,
"max_line_length": 99,
"avg_line_length": 39.59574468085106,
"alnum_prop": 0.7684040838259001,
"repo_name": "brettwooldridge/buck",
"id": "2a68292215b22bb9baa38809077b864256af9299",
"size": "2466",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/com/facebook/buck/rules/modern/config/ModernBuildRuleStrategyConfigFromSection.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "1585"
},
{
"name": "Batchfile",
"bytes": "3875"
},
{
"name": "C",
"bytes": "280326"
},
{
"name": "C#",
"bytes": "237"
},
{
"name": "C++",
"bytes": "18771"
},
{
"name": "CSS",
"bytes": "56106"
},
{
"name": "D",
"bytes": "1017"
},
{
"name": "Dockerfile",
"bytes": "2081"
},
{
"name": "Go",
"bytes": "9822"
},
{
"name": "Groovy",
"bytes": "3362"
},
{
"name": "HTML",
"bytes": "10916"
},
{
"name": "Haskell",
"bytes": "1008"
},
{
"name": "IDL",
"bytes": "480"
},
{
"name": "Java",
"bytes": "28622919"
},
{
"name": "JavaScript",
"bytes": "938678"
},
{
"name": "Kotlin",
"bytes": "23444"
},
{
"name": "Lex",
"bytes": "7502"
},
{
"name": "MATLAB",
"bytes": "47"
},
{
"name": "Makefile",
"bytes": "1916"
},
{
"name": "OCaml",
"bytes": "4935"
},
{
"name": "Objective-C",
"bytes": "176943"
},
{
"name": "Objective-C++",
"bytes": "34"
},
{
"name": "PowerShell",
"bytes": "2244"
},
{
"name": "Python",
"bytes": "2069290"
},
{
"name": "Roff",
"bytes": "1207"
},
{
"name": "Rust",
"bytes": "5214"
},
{
"name": "Scala",
"bytes": "5082"
},
{
"name": "Shell",
"bytes": "76854"
},
{
"name": "Smalltalk",
"bytes": "194"
},
{
"name": "Swift",
"bytes": "11393"
},
{
"name": "Thrift",
"bytes": "47828"
},
{
"name": "Yacc",
"bytes": "323"
}
],
"symlink_target": ""
} |
package proto
//go:generate cproto
| {
"content_hash": "484bdabf67cdbda6610fe2f9e3743822",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 20,
"avg_line_length": 12,
"alnum_prop": 0.7777777777777778,
"repo_name": "luci/luci-go",
"id": "1b26f48d5ba736df11fd0ed47893be5671631e69",
"size": "686",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "common/proto/doc.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "25460"
},
{
"name": "Go",
"bytes": "10674259"
},
{
"name": "HTML",
"bytes": "658081"
},
{
"name": "JavaScript",
"bytes": "18433"
},
{
"name": "Makefile",
"bytes": "2862"
},
{
"name": "Python",
"bytes": "49205"
},
{
"name": "Shell",
"bytes": "20986"
},
{
"name": "TypeScript",
"bytes": "110221"
}
],
"symlink_target": ""
} |
class BinaryDiagnostic
def initialize
@input = File.readlines('input').map { |n| n.strip }
end
def gamma_epsilon_product
original_input = @input.dup
reduce_via { |zero_counter, half_input_len| zero_counter <= half_input_len ? '1' : '0' }
oxygen_generator_rating = @input[0]
@input = original_input
reduce_via { |zero_counter, half_input_len| zero_counter <= half_input_len ? '0' : '1' }
co2_scrubber_rating = @input[0]
oxygen_generator_rating.to_i(2) * co2_scrubber_rating.to_i(2)
end
private
def reduce_via
@input.first.size.times do |i|
break if @input.size == 1
zero_counter = count_zeros_at_position(i)
half_input_len = @input.size / 2.0
selected_value = yield(zero_counter, half_input_len)
@input.select! { |row| row[i] == selected_value }
end
end
def count_zeros_at_position(position)
@input.select { |num| num[position] == '0' }.count
end
end
puts BinaryDiagnostic.new.gamma_epsilon_product
| {
"content_hash": "f4d31cd1561ff599fde7531721f57f05",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 92,
"avg_line_length": 26.31578947368421,
"alnum_prop": 0.645,
"repo_name": "khall/advent_of_code",
"id": "eff08cae785130c3f9136fcdb7b17de16e9cb8bf",
"size": "1000",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "2021/3/b.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "155825"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j='http://jakarta.apache.org/log4j/'>
<appender name="console" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.EnhancedPatternLayout">
<param name="ConversionPattern" value="%d{MM-dd HH:mm:ss} [%-5p](%-35c{1.}:%L) %m%n"/>
</layout>
</appender>
<appender name="stat-appender" class="org.apache.log4j.DailyRollingFileAppender">
<param name="file" value="${catalina.home}/logs/stat.log"/>
<param name="Append" value="true"/>
<param name="DatePattern" value="'.'yyyy-MM-dd"/>
<layout class="org.apache.log4j.EnhancedPatternLayout">
<param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} [%-5p](%-35c{1.}) %m%n"/>
</layout>
</appender>
<logger name="com.navercorp.pinpoint" additivity="false">
<level value="DEBUG"/>
<appender-ref ref="console"/>
</logger>
<logger name="com.navercorp.pinpoint.collector.dao" additivity="false">
<level value="TRACE"/>
<appender-ref ref="console"/>
</logger>
<logger name="org.apache.zookeeper" additivity="false">
<level value="INFO"/>
<appender-ref ref="console"/>
</logger>
<logger name="org.apache.hadoop.hbase" additivity="false">
<level value="INFO"/>
<appender-ref ref="console"/>
</logger>
<logger name="com.navercorp.pinpoint.collector.StateReport" additivity="false">
<level value="WARN"/>
<appender-ref ref="stat-appender"/>
</logger>
<root>
<level value="INFO"/>
<appender-ref ref="console"/>
</root>
</log4j:configuration> | {
"content_hash": "66455883faa12564560f39d2a9e0430d",
"timestamp": "",
"source": "github",
"line_count": 51,
"max_line_length": 100,
"avg_line_length": 34.666666666666664,
"alnum_prop": 0.6148190045248869,
"repo_name": "carpedm20/pinpoint",
"id": "8c3e516cb3f4cca2917beb5a382525ccb49e040a",
"size": "1768",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "collector/src/main/resources/log4j.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "163098"
},
{
"name": "CoffeeScript",
"bytes": "10124"
},
{
"name": "Groovy",
"bytes": "1423"
},
{
"name": "HTML",
"bytes": "982261"
},
{
"name": "Java",
"bytes": "5744100"
},
{
"name": "JavaScript",
"bytes": "2894123"
},
{
"name": "Makefile",
"bytes": "15485"
},
{
"name": "Python",
"bytes": "11423"
},
{
"name": "Shell",
"bytes": "65205"
},
{
"name": "Thrift",
"bytes": "5508"
}
],
"symlink_target": ""
} |
/**
* Benchmark `real`.
*/
#include "stdlib/complex/real.h"
#include "stdlib/complex/float64.h"
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <time.h>
#include <complex.h>
#include <sys/time.h>
#define NAME "real"
#define ITERATIONS 1000000
#define REPEATS 3
/**
* Prints the TAP version.
*/
void print_version() {
printf( "TAP version 13\n" );
}
/**
* Prints the TAP summary.
*
* @param total total number of tests
* @param passing total number of passing tests
*/
void print_summary( int total, int passing ) {
printf( "#\n" );
printf( "1..%d\n", total ); // TAP plan
printf( "# total %d\n", total );
printf( "# pass %d\n", passing );
printf( "#\n" );
printf( "# ok\n" );
}
/**
* Prints benchmarks results.
*
* @param elapsed elapsed time in seconds
*/
void print_results( double elapsed ) {
double rate = (double)ITERATIONS / elapsed;
printf( " ---\n" );
printf( " iterations: %d\n", ITERATIONS );
printf( " elapsed: %0.9f\n", elapsed );
printf( " rate: %0.9f\n", rate );
printf( " ...\n" );
}
/**
* Returns a clock time.
*
* @return clock time
*/
double tic() {
struct timeval now;
gettimeofday( &now, NULL );
return (double)now.tv_sec + (double)now.tv_usec/1.0e6;
}
/**
* Generates a random number on the interval [0,1].
*
* @return random number
*/
double rand_double() {
int r = rand();
return (double)r / ( (double)RAND_MAX + 1.0 );
}
/**
* Runs a benchmark.
*
* @return elapsed time in seconds
*/
double benchmark() {
stdlib_complex128_t z;
double elapsed;
double re;
double im;
double v;
double t;
int i;
t = tic();
for ( i = 0; i < ITERATIONS; i++ ) {
re = rand_double();
im = rand_double();
z = stdlib_complex128( re, im );
v = stdlib_real( z );
if ( v != v ) {
printf( "should not return NaN\n" );
break;
}
}
elapsed = tic() - t;
if ( v != v ) {
printf( "should not return NaN\n" );
}
return elapsed;
}
/**
* Main execution sequence.
*/
int main( void ) {
double elapsed;
int i;
// Use the current time to seed the random number generator:
srand( time( NULL ) );
print_version();
for ( i = 0; i < REPEATS; i++ ) {
printf( "# c::native::%s\n", NAME );
elapsed = benchmark();
print_results( elapsed );
printf( "ok %d benchmark finished\n", i+1 );
}
print_summary( REPEATS, REPEATS );
}
| {
"content_hash": "f905964e1b8e7c96954d9bd83986c802",
"timestamp": "",
"source": "github",
"line_count": 126,
"max_line_length": 61,
"avg_line_length": 18.349206349206348,
"alnum_prop": 0.6068339100346021,
"repo_name": "stdlib-js/stdlib",
"id": "b99098b20c394be52dccb02057800a9378d5c67b",
"size": "2928",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "lib/node_modules/@stdlib/complex/real/benchmark/c/native/benchmark.c",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Awk",
"bytes": "21739"
},
{
"name": "C",
"bytes": "15336495"
},
{
"name": "C++",
"bytes": "1349482"
},
{
"name": "CSS",
"bytes": "58039"
},
{
"name": "Fortran",
"bytes": "198059"
},
{
"name": "HTML",
"bytes": "56181"
},
{
"name": "Handlebars",
"bytes": "16114"
},
{
"name": "JavaScript",
"bytes": "85975525"
},
{
"name": "Julia",
"bytes": "1508654"
},
{
"name": "Makefile",
"bytes": "4806816"
},
{
"name": "Python",
"bytes": "3343697"
},
{
"name": "R",
"bytes": "576612"
},
{
"name": "Shell",
"bytes": "559315"
},
{
"name": "TypeScript",
"bytes": "19309407"
},
{
"name": "WebAssembly",
"bytes": "5980"
}
],
"symlink_target": ""
} |
require 'action_view/helpers/javascript_helper'
require 'active_support/core_ext/array/access'
require 'active_support/core_ext/hash/keys'
require 'action_dispatch'
module ActionView
# = Action View URL Helpers
module Helpers #:nodoc:
# Provides a set of methods for making links and getting URLs that
# depend on the routing subsystem (see ActionDispatch::Routing).
# This allows you to use the same format for links in views
# and controllers.
module UrlHelper
# This helper may be included in any class that includes the
# URL helpers of a routes (routes.url_helpers). Some methods
# provided here will only work in the4 context of a request
# (link_to_unless_current, for instance), which must be provided
# as a method called #request on the context.
extend ActiveSupport::Concern
include ActionDispatch::Routing::UrlFor
include TagHelper
# Need to map default url options to controller one.
# def default_url_options(*args) #:nodoc:
# controller.send(:default_url_options, *args)
# end
#
def url_options
return super unless controller.respond_to?(:url_options)
controller.url_options
end
# Returns the URL for the set of +options+ provided. This takes the
# same options as +url_for+ in Action Controller (see the
# documentation for <tt>ActionController::Base#url_for</tt>). Note that by default
# <tt>:only_path</tt> is <tt>true</tt> so you'll get the relative "/controller/action"
# instead of the fully qualified URL like "http://example.com/controller/action".
#
# ==== Options
# * <tt>:anchor</tt> - Specifies the anchor name to be appended to the path.
# * <tt>:only_path</tt> - If true, returns the relative URL (omitting the protocol, host name, and port) (<tt>true</tt> by default unless <tt>:host</tt> is specified).
# * <tt>:trailing_slash</tt> - If true, adds a trailing slash, as in "/archive/2005/". Note that this
# is currently not recommended since it breaks caching.
# * <tt>:host</tt> - Overrides the default (current) host if provided.
# * <tt>:protocol</tt> - Overrides the default (current) protocol if provided.
# * <tt>:user</tt> - Inline HTTP authentication (only plucked out if <tt>:password</tt> is also present).
# * <tt>:password</tt> - Inline HTTP authentication (only plucked out if <tt>:user</tt> is also present).
#
# ==== Relying on named routes
#
# If you instead of a hash pass a record (like an Active Record or Active Resource) as the options parameter,
# you'll trigger the named route for that record. The lookup will happen on the name of the class. So passing
# a Workshop object will attempt to use the +workshop_path+ route. If you have a nested route, such as
# +admin_workshop_path+ you'll have to call that explicitly (it's impossible for +url_for+ to guess that route).
#
# ==== Examples
# <%= url_for(:action => 'index') %>
# # => /blog/
#
# <%= url_for(:action => 'find', :controller => 'books') %>
# # => /books/find
#
# <%= url_for(:action => 'login', :controller => 'members', :only_path => false, :protocol => 'https') %>
# # => https://www.railsapplication.com/members/login/
#
# <%= url_for(:action => 'play', :anchor => 'player') %>
# # => /messages/play/#player
#
# <%= url_for(:action => 'jump', :anchor => 'tax&ship') %>
# # => /testing/jump/#tax&ship
#
# <%= url_for(Workshop.new) %>
# # relies on Workshop answering a persisted? call (and in this case returning false)
# # => /workshops
#
# <%= url_for(@workshop) %>
# # calls @workshop.to_s
# # => /workshops/5
#
# <%= url_for("http://www.example.com") %>
# # => http://www.example.com
#
# <%= url_for(:back) %>
# # if request.env["HTTP_REFERER"] is set to "http://www.example.com"
# # => http://www.example.com
#
# <%= url_for(:back) %>
# # if request.env["HTTP_REFERER"] is not set or is blank
# # => javascript:history.back()
def url_for(options = {})
options ||= {}
url = case options
when String
options
when Hash
options = options.symbolize_keys.reverse_merge!(:only_path => options[:host].nil?)
super
when :back
controller.request.env["HTTP_REFERER"] || 'javascript:history.back()'
else
polymorphic_path(options)
end
url
end
# Creates a link tag of the given +name+ using a URL created by the set
# of +options+. See the valid options in the documentation for
# +url_for+. It's also possible to pass a string instead
# of an options hash to get a link tag that uses the value of the string as the
# href for the link, or use <tt>:back</tt> to link to the referrer - a JavaScript back
# link will be used in place of a referrer if none exists. If +nil+ is passed as
# a name, the link itself will become the name.
#
# ==== Signatures
#
# link_to(body, url, html_options = {})
# # url is a String; you can use URL helpers like
# # posts_path
#
# link_to(body, url_options = {}, html_options = {})
# # url_options, except :confirm or :method,
# # is passed to url_for
#
# link_to(options = {}, html_options = {}) do
# # name
# end
#
# link_to(url, html_options = {}) do
# # name
# end
#
# ==== Options
# * <tt>:confirm => 'question?'</tt> - This will allow the unobtrusive JavaScript
# driver to prompt with the question specified. If the user accepts, the link is
# processed normally, otherwise no action is taken.
# * <tt>:method => symbol of HTTP verb</tt> - This modifier will dynamically
# create an HTML form and immediately submit the form for processing using
# the HTTP verb specified. Useful for having links perform a POST operation
# in dangerous actions like deleting a record (which search bots can follow
# while spidering your site). Supported verbs are <tt>:post</tt>, <tt>:delete</tt> and <tt>:put</tt>.
# Note that if the user has JavaScript disabled, the request will fall back
# to using GET. If <tt>:href => '#'</tt> is used and the user has JavaScript
# disabled clicking the link will have no effect. If you are relying on the
# POST behavior, you should check for it in your controller's action by using
# the request object's methods for <tt>post?</tt>, <tt>delete?</tt> or <tt>put?</tt>.
# * <tt>:remote => true</tt> - This will allow the unobtrusive JavaScript
# driver to make an Ajax request to the URL in question instead of following
# the link. The drivers each provide mechanisms for listening for the
# completion of the Ajax request and performing JavaScript operations once
# they're complete
#
# ==== Examples
# Because it relies on +url_for+, +link_to+ supports both older-style controller/action/id arguments
# and newer RESTful routes. Current Rails style favors RESTful routes whenever possible, so base
# your application on resources and use
#
# link_to "Profile", profile_path(@profile)
# # => <a href="/profiles/1">Profile</a>
#
# or the even pithier
#
# link_to "Profile", @profile
# # => <a href="/profiles/1">Profile</a>
#
# in place of the older more verbose, non-resource-oriented
#
# link_to "Profile", :controller => "profiles", :action => "show", :id => @profile
# # => <a href="/profiles/show/1">Profile</a>
#
# Similarly,
#
# link_to "Profiles", profiles_path
# # => <a href="/profiles">Profiles</a>
#
# is better than
#
# link_to "Profiles", :controller => "profiles"
# # => <a href="/profiles">Profiles</a>
#
# You can use a block as well if your link target is hard to fit into the name parameter. ERb example:
#
# <%= link_to(@profile) do %>
# <strong><%= @profile.name %></strong> -- <span>Check it out!</span>
# <% end %>
# # => <a href="/profiles/1">
# <strong>David</strong> -- <span>Check it out!</span>
# </a>
#
# Classes and ids for CSS are easy to produce:
#
# link_to "Articles", articles_path, :id => "news", :class => "article"
# # => <a href="/articles" class="article" id="news">Articles</a>
#
# Be careful when using the older argument style, as an extra literal hash is needed:
#
# link_to "Articles", { :controller => "articles" }, :id => "news", :class => "article"
# # => <a href="/articles" class="article" id="news">Articles</a>
#
# Leaving the hash off gives the wrong link:
#
# link_to "WRONG!", :controller => "articles", :id => "news", :class => "article"
# # => <a href="/articles/index/news?class=article">WRONG!</a>
#
# +link_to+ can also produce links with anchors or query strings:
#
# link_to "Comment wall", profile_path(@profile, :anchor => "wall")
# # => <a href="/profiles/1#wall">Comment wall</a>
#
# link_to "Ruby on Rails search", :controller => "searches", :query => "ruby on rails"
# # => <a href="/searches?query=ruby+on+rails">Ruby on Rails search</a>
#
# link_to "Nonsense search", searches_path(:foo => "bar", :baz => "quux")
# # => <a href="/searches?foo=bar&baz=quux">Nonsense search</a>
#
# The two options specific to +link_to+ (<tt>:confirm</tt> and <tt>:method</tt>) are used as follows:
#
# link_to "Visit Other Site", "http://www.rubyonrails.org/", :confirm => "Are you sure?"
# # => <a href="http://www.rubyonrails.org/" data-confirm="Are you sure?"">Visit Other Site</a>
#
# link_to("Destroy", "http://www.example.com", :method => :delete, :confirm => "Are you sure?")
# # => <a href='http://www.example.com' rel="nofollow" data-method="delete" data-confirm="Are you sure?">Destroy</a>
def link_to(*args, &block)
if block_given?
options = args.first || {}
html_options = args.second
link_to(capture(&block), options, html_options)
else
name = args[0]
options = args[1] || {}
html_options = args[2]
html_options = convert_options_to_data_attributes(options, html_options)
url = url_for(options)
if html_options
html_options = html_options.stringify_keys
href = html_options['href']
tag_options = tag_options(html_options)
else
tag_options = nil
end
href_attr = "href=\"#{html_escape(url)}\"" unless href
"<a #{href_attr}#{tag_options}>#{html_escape(name || url)}</a>".html_safe
end
end
# Generates a form containing a single button that submits to the URL created
# by the set of +options+. This is the safest method to ensure links that
# cause changes to your data are not triggered by search bots or accelerators.
# If the HTML button does not work with your layout, you can also consider
# using the +link_to+ method with the <tt>:method</tt> modifier as described in
# the +link_to+ documentation.
#
# The generated form element has a class name of <tt>button_to</tt>
# to allow styling of the form itself and its children. You can control
# the form submission and input element behavior using +html_options+.
# This method accepts the <tt>:method</tt> and <tt>:confirm</tt> modifiers
# described in the +link_to+ documentation. If no <tt>:method</tt> modifier
# is given, it will default to performing a POST operation. You can also
# disable the button by passing <tt>:disabled => true</tt> in +html_options+.
# If you are using RESTful routes, you can pass the <tt>:method</tt>
# to change the HTTP verb used to submit the form.
#
# ==== Options
# The +options+ hash accepts the same options as url_for.
#
# There are a few special +html_options+:
# * <tt>:method</tt> - Specifies the anchor name to be appended to the path.
# * <tt>:disabled</tt> - Specifies the anchor name to be appended to the path.
# * <tt>:confirm</tt> - This will use the unobtrusive JavaScript driver to
# prompt with the question specified. If the user accepts, the link is
# processed normally, otherwise no action is taken.
# * <tt>:remote</tt> - If set to true, will allow the Unobtrusive JavaScript drivers to control the
# submit behaviour. By default this behaviour is an ajax submit.
#
# ==== Examples
# <%= button_to "New", :action => "new" %>
# # => "<form method="post" action="/controller/new" class="button_to">
# # <div><input value="New" type="submit" /></div>
# # </form>"
#
#
# <%= button_to "Delete Image", { :action => "delete", :id => @image.id },
# :confirm => "Are you sure?", :method => :delete %>
# # => "<form method="post" action="/images/delete/1" class="button_to">
# # <div>
# # <input type="hidden" name="_method" value="delete" />
# # <input data-confirm='Are you sure?' value="Delete" type="submit" />
# # </div>
# # </form>"
#
#
# <%= button_to('Destroy', 'http://www.example.com', :confirm => 'Are you sure?',
# :method => "delete", :remote => true, :disable_with => 'loading...') %>
# # => "<form class='button_to' method='post' action='http://www.example.com' data-remote='true'>
# # <div>
# # <input name='_method' value='delete' type='hidden' />
# # <input value='Destroy' type='submit' disable_with='loading...' data-confirm='Are you sure?' />
# # </div>
# # </form>"
# #
def button_to(name, options = {}, html_options = {})
html_options = html_options.stringify_keys
convert_boolean_attributes!(html_options, %w( disabled ))
method_tag = ''
if (method = html_options.delete('method')) && %w{put delete}.include?(method.to_s)
method_tag = tag('input', :type => 'hidden', :name => '_method', :value => method.to_s)
end
form_method = method.to_s == 'get' ? 'get' : 'post'
remote = html_options.delete('remote')
request_token_tag = ''
if form_method == 'post' && protect_against_forgery?
request_token_tag = tag(:input, :type => "hidden", :name => request_forgery_protection_token.to_s, :value => form_authenticity_token)
end
url = options.is_a?(String) ? options : self.url_for(options)
name ||= url
html_options = convert_options_to_data_attributes(options, html_options)
html_options.merge!("type" => "submit", "value" => name)
("<form method=\"#{form_method}\" action=\"#{html_escape(url)}\" #{"data-remote=\"true\"" if remote} class=\"button_to\"><div>" +
method_tag + tag("input", html_options) + request_token_tag + "</div></form>").html_safe
end
# Creates a link tag of the given +name+ using a URL created by the set of
# +options+ unless the current request URI is the same as the links, in
# which case only the name is returned (or the given block is yielded, if
# one exists). You can give +link_to_unless_current+ a block which will
# specialize the default behavior (e.g., show a "Start Here" link rather
# than the link's text).
#
# ==== Examples
# Let's say you have a navigation menu...
#
# <ul id="navbar">
# <li><%= link_to_unless_current("Home", { :action => "index" }) %></li>
# <li><%= link_to_unless_current("About Us", { :action => "about" }) %></li>
# </ul>
#
# If in the "about" action, it will render...
#
# <ul id="navbar">
# <li><a href="/controller/index">Home</a></li>
# <li>About Us</li>
# </ul>
#
# ...but if in the "index" action, it will render:
#
# <ul id="navbar">
# <li>Home</li>
# <li><a href="/controller/about">About Us</a></li>
# </ul>
#
# The implicit block given to +link_to_unless_current+ is evaluated if the current
# action is the action given. So, if we had a comments page and wanted to render a
# "Go Back" link instead of a link to the comments page, we could do something like this...
#
# <%=
# link_to_unless_current("Comment", { :controller => "comments", :action => "new" }) do
# link_to("Go back", { :controller => "posts", :action => "index" })
# end
# %>
def link_to_unless_current(name, options = {}, html_options = {}, &block)
link_to_unless current_page?(options), name, options, html_options, &block
end
# Creates a link tag of the given +name+ using a URL created by the set of
# +options+ unless +condition+ is true, in which case only the name is
# returned. To specialize the default behavior (i.e., show a login link rather
# than just the plaintext link text), you can pass a block that
# accepts the name or the full argument list for +link_to_unless+.
#
# ==== Examples
# <%= link_to_unless(@current_user.nil?, "Reply", { :action => "reply" }) %>
# # If the user is logged in...
# # => <a href="/controller/reply/">Reply</a>
#
# <%=
# link_to_unless(@current_user.nil?, "Reply", { :action => "reply" }) do |name|
# link_to(name, { :controller => "accounts", :action => "signup" })
# end
# %>
# # If the user is logged in...
# # => <a href="/controller/reply/">Reply</a>
# # If not...
# # => <a href="/accounts/signup">Reply</a>
def link_to_unless(condition, name, options = {}, html_options = {}, &block)
if condition
if block_given?
block.arity <= 1 ? capture(name, &block) : capture(name, options, html_options, &block)
else
name
end
else
link_to(name, options, html_options)
end
end
# Creates a link tag of the given +name+ using a URL created by the set of
# +options+ if +condition+ is true, in which case only the name is
# returned. To specialize the default behavior, you can pass a block that
# accepts the name or the full argument list for +link_to_unless+ (see the examples
# in +link_to_unless+).
#
# ==== Examples
# <%= link_to_if(@current_user.nil?, "Login", { :controller => "sessions", :action => "new" }) %>
# # If the user isn't logged in...
# # => <a href="/sessions/new/">Login</a>
#
# <%=
# link_to_if(@current_user.nil?, "Login", { :controller => "sessions", :action => "new" }) do
# link_to(@current_user.login, { :controller => "accounts", :action => "show", :id => @current_user })
# end
# %>
# # If the user isn't logged in...
# # => <a href="/sessions/new/">Login</a>
# # If they are logged in...
# # => <a href="/accounts/show/3">my_username</a>
def link_to_if(condition, name, options = {}, html_options = {}, &block)
link_to_unless !condition, name, options, html_options, &block
end
# Creates a mailto link tag to the specified +email_address+, which is
# also used as the name of the link unless +name+ is specified. Additional
# HTML attributes for the link can be passed in +html_options+.
#
# +mail_to+ has several methods for hindering email harvesters and customizing
# the email itself by passing special keys to +html_options+.
#
# ==== Options
# * <tt>:encode</tt> - This key will accept the strings "javascript" or "hex".
# Passing "javascript" will dynamically create and encode the mailto link then
# eval it into the DOM of the page. This method will not show the link on
# the page if the user has JavaScript disabled. Passing "hex" will hex
# encode the +email_address+ before outputting the mailto link.
# * <tt>:replace_at</tt> - When the link +name+ isn't provided, the
# +email_address+ is used for the link label. You can use this option to
# obfuscate the +email_address+ by substituting the @ sign with the string
# given as the value.
# * <tt>:replace_dot</tt> - When the link +name+ isn't provided, the
# +email_address+ is used for the link label. You can use this option to
# obfuscate the +email_address+ by substituting the . in the email with the
# string given as the value.
# * <tt>:subject</tt> - Preset the subject line of the email.
# * <tt>:body</tt> - Preset the body of the email.
# * <tt>:cc</tt> - Carbon Copy addition recipients on the email.
# * <tt>:bcc</tt> - Blind Carbon Copy additional recipients on the email.
#
# ==== Examples
# mail_to "me@domain.com"
# # => <a href="mailto:me@domain.com">me@domain.com</a>
#
# mail_to "me@domain.com", "My email", :encode => "javascript"
# # => <script type="text/javascript">eval(decodeURIComponent('%64%6f%63...%27%29%3b'))</script>
#
# mail_to "me@domain.com", "My email", :encode => "hex"
# # => <a href="mailto:%6d%65@%64%6f%6d%61%69%6e.%63%6f%6d">My email</a>
#
# mail_to "me@domain.com", nil, :replace_at => "_at_", :replace_dot => "_dot_", :class => "email"
# # => <a href="mailto:me@domain.com" class="email">me_at_domain_dot_com</a>
#
# mail_to "me@domain.com", "My email", :cc => "ccaddress@domain.com",
# :subject => "This is an example email"
# # => <a href="mailto:me@domain.com?cc=ccaddress@domain.com&subject=This%20is%20an%20example%20email">My email</a>
def mail_to(email_address, name = nil, html_options = {})
email_address = html_escape(email_address)
html_options = html_options.stringify_keys
encode = html_options.delete("encode").to_s
cc, bcc, subject, body = html_options.delete("cc"), html_options.delete("bcc"), html_options.delete("subject"), html_options.delete("body")
extras = []
extras << "cc=#{Rack::Utils.escape(cc).gsub("+", "%20")}" unless cc.nil?
extras << "bcc=#{Rack::Utils.escape(bcc).gsub("+", "%20")}" unless bcc.nil?
extras << "body=#{Rack::Utils.escape(body).gsub("+", "%20")}" unless body.nil?
extras << "subject=#{Rack::Utils.escape(subject).gsub("+", "%20")}" unless subject.nil?
extras = extras.empty? ? '' : '?' + html_escape(extras.join('&'))
email_address_obfuscated = email_address.dup
email_address_obfuscated.gsub!(/@/, html_options.delete("replace_at")) if html_options.has_key?("replace_at")
email_address_obfuscated.gsub!(/\./, html_options.delete("replace_dot")) if html_options.has_key?("replace_dot")
string = ''
if encode == "javascript"
"document.write('#{content_tag("a", name || email_address_obfuscated.html_safe, html_options.merge("href" => "mailto:#{email_address}#{extras}".html_safe))}');".each_byte do |c|
string << sprintf("%%%x", c)
end
"<script type=\"#{Mime::JS}\">eval(decodeURIComponent('#{string}'))</script>".html_safe
elsif encode == "hex"
email_address_encoded = ''
email_address_obfuscated.each_byte do |c|
email_address_encoded << sprintf("&#%d;", c)
end
protocol = 'mailto:'
protocol.each_byte { |c| string << sprintf("&#%d;", c) }
email_address.each_byte do |c|
char = c.chr
string << (char =~ /\w/ ? sprintf("%%%x", c) : char)
end
content_tag "a", name || email_address_encoded.html_safe, html_options.merge("href" => "#{string}#{extras}".html_safe)
else
content_tag "a", name || email_address_obfuscated.html_safe, html_options.merge("href" => "mailto:#{email_address}#{extras}".html_safe)
end
end
# True if the current request URI was generated by the given +options+.
#
# ==== Examples
# Let's say we're in the <tt>/shop/checkout?order=desc</tt> action.
#
# current_page?(:action => 'process')
# # => false
#
# current_page?(:controller => 'shop', :action => 'checkout')
# # => true
#
# current_page?(:controller => 'shop', :action => 'checkout', :order => 'asc')
# # => false
#
# current_page?(:action => 'checkout')
# # => true
#
# current_page?(:controller => 'library', :action => 'checkout')
# # => false
#
# Let's say we're in the <tt>/shop/checkout?order=desc&page=1</tt> action.
#
# current_page?(:action => 'process')
# # => false
#
# current_page?(:controller => 'shop', :action => 'checkout')
# # => true
#
# current_page?(:controller => 'shop', :action => 'checkout', :order => 'desc', :page=>'1')
# # => true
#
# current_page?(:controller => 'shop', :action => 'checkout', :order => 'desc', :page=>'2')
# # => false
#
# current_page?(:controller => 'shop', :action => 'checkout', :order => 'desc')
# # => false
#
# current_page?(:action => 'checkout')
# # => true
#
# current_page?(:controller => 'library', :action => 'checkout')
# # => false
def current_page?(options)
unless request
raise "You cannot use helpers that need to determine the current " \
"page unless your view context provides a Request object " \
"in a #request method"
end
url_string = url_for(options)
# We ignore any extra parameters in the request_uri if the
# submitted url doesn't have any either. This lets the function
# work with things like ?order=asc
if url_string.index("?")
request_uri = request.fullpath
else
request_uri = request.path
end
if url_string =~ /^\w+:\/\//
url_string == "#{request.protocol}#{request.host_with_port}#{request_uri}"
else
url_string == request_uri
end
end
private
def convert_options_to_data_attributes(options, html_options)
html_options = {} if html_options.nil?
html_options = html_options.stringify_keys
if (options.is_a?(Hash) && options.key?('remote') && options.delete('remote')) || (html_options.is_a?(Hash) && html_options.key?('remote') && html_options.delete('remote'))
html_options['data-remote'] = 'true'
end
confirm = html_options.delete("confirm")
if html_options.key?("popup")
ActiveSupport::Deprecation.warn(":popup has been deprecated", caller)
end
method, href = html_options.delete("method"), html_options['href']
add_confirm_to_attributes!(html_options, confirm) if confirm
add_method_to_attributes!(html_options, method) if method
html_options
end
def add_confirm_to_attributes!(html_options, confirm)
html_options["data-confirm"] = confirm if confirm
end
def add_method_to_attributes!(html_options, method)
html_options["rel"] = "nofollow" if method && method.to_s.downcase != "get"
html_options["data-method"] = method if method
end
def options_for_javascript(options)
if options.empty?
'{}'
else
"{#{options.keys.map { |k| "#{k}:#{options[k]}" }.sort.join(', ')}}"
end
end
def array_or_string_for_javascript(option)
if option.kind_of?(Array)
"['#{option.join('\',\'')}']"
elsif !option.nil?
"'#{option}'"
end
end
# Processes the +html_options+ hash, converting the boolean
# attributes from true/false form into the form required by
# HTML/XHTML. (An attribute is considered to be boolean if
# its name is listed in the given +bool_attrs+ array.)
#
# More specifically, for each boolean attribute in +html_options+
# given as:
#
# "attr" => bool_value
#
# if the associated +bool_value+ evaluates to true, it is
# replaced with the attribute's name; otherwise the attribute is
# removed from the +html_options+ hash. (See the XHTML 1.0 spec,
# section 4.5 "Attribute Minimization" for more:
# http://www.w3.org/TR/xhtml1/#h-4.5)
#
# Returns the updated +html_options+ hash, which is also modified
# in place.
#
# Example:
#
# convert_boolean_attributes!( html_options,
# %w( checked disabled readonly ) )
def convert_boolean_attributes!(html_options, bool_attrs)
bool_attrs.each { |x| html_options[x] = x if html_options.delete(x) }
html_options
end
end
end
end
| {
"content_hash": "1dc61e4dfa27ba850e41939e9b9508c2",
"timestamp": "",
"source": "github",
"line_count": 664,
"max_line_length": 187,
"avg_line_length": 45.38403614457831,
"alnum_prop": 0.5673137547702007,
"repo_name": "Vizzuality/ushelf",
"id": "b0401c985913d1825e97db1a394e8f31affab9af",
"size": "30135",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "rmagick/ruby/1.8/gems/actionpack-3.0.1/lib/action_view/helpers/url_helper.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "926050"
},
{
"name": "JavaScript",
"bytes": "1535612"
},
{
"name": "PHP",
"bytes": "1205"
},
{
"name": "Ruby",
"bytes": "11905086"
},
{
"name": "Shell",
"bytes": "13362"
}
],
"symlink_target": ""
} |
<p><code><test a="</code> content of attribute <code>"></code></p>
<p>Fix for backticks within HTML tag: <span attr='`ticks`'>like this</span></p>
<p>Here's how you put <code>`backticks`</code> in a code span.</p>
| {
"content_hash": "84fcc5074678c00ab51544089c6f03e9",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 79,
"avg_line_length": 45.4,
"alnum_prop": 0.6343612334801763,
"repo_name": "Bunk/farse",
"id": "b6950fd6e3fd4a32d1a5fb9b5c110e7ce1f1b0b4",
"size": "227",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "tests/testfiles/mdtest-1.1/Code_Spans.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "F#",
"bytes": "72350"
}
],
"symlink_target": ""
} |
package nu.aron.kataromannumerals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import io.vavr.CheckedFunction1;
import io.vavr.test.Arbitrary;
import io.vavr.test.Property;
class MainTest {
Main testee;
@BeforeEach
void setUp() {
testee = new Main();
}
@Test
void multipleChars() {
assertEquals("MM", testee.charMultiple.apply(2, "M"));
assertEquals("", testee.charMultiple.apply(0, "C"));
}
@Test
void thousands() {
assertEquals("MM", testee.mille.apply(2000));
}
@Test
void testThrees() {
var numbers = Arbitrary.integer()
.filter(i -> i < 3000)
.filter(i -> i > 0)
.filter(i -> i % 10 == 3);
CheckedFunction1<Integer, Boolean> threeIsIII = i -> testee.numeral(i).endsWith("III");
var result = Property.def("threes")
.forAll(numbers)
.suchThat(threeIsIII)
.check();
var sample = result.sample();
sample.stdout();
result.assertIsSatisfied();
}
@Test
void testFives() {
var numbers = Arbitrary.integer()
.filter(i -> i < 3000)
.filter(i -> i > 0)
.filter(i -> i % 10 == 5);
CheckedFunction1<Integer, Boolean> fiveIsV = i -> testee.numeral(i).endsWith("V");
var result = Property.def("fives")
.forAll(numbers)
.suchThat(fiveIsV)
.check();
var sample = result.sample();
sample.stdout();
result.assertIsSatisfied();
}
@Test
void testOnes() {
var numbers = Arbitrary.integer()
.filter(i -> i < 3000)
.filter(i -> i > 0)
.filter(i -> i % 10 == 1);
CheckedFunction1<Integer, Boolean> oneIsI = i -> testee.numeral(i).endsWith("I");
var result = Property.def("ones")
.forAll(numbers)
.suchThat(oneIsI)
.check();
var sample = result.sample();
sample.stdout();
result.assertIsSatisfied();
}
@Test
void examples() {
assertEquals("I", testee.numeral(1));
assertEquals("II", testee.numeral(2));
assertEquals("III", testee.numeral(3));
assertEquals("IV", testee.numeral(4));
assertEquals("V", testee.numeral(5));
assertEquals("VI", testee.numeral(6));
assertEquals("VII", testee.numeral(7));
assertEquals("VIII", testee.numeral(8));
assertEquals("IX", testee.numeral(9));
assertEquals("X", testee.numeral(10));
assertEquals("XIX", testee.numeral(19));
assertEquals("XLIX", testee.numeral(49));
assertEquals("XCIX", testee.numeral(99));
assertEquals("CCCIX", testee.numeral(309));
assertEquals("DXXVII", testee.numeral(527));
assertEquals("DCCLXXXIX", testee.numeral(789));
assertEquals("MDCCCLXXXVIII", testee.numeral(1888));
assertEquals("MCMXCIX", testee.numeral(1999));
assertEquals("MMI", testee.numeral(2001));
}
}
| {
"content_hash": "fa77cebda9a8e8971f1e83a4201ad31e",
"timestamp": "",
"source": "github",
"line_count": 102,
"max_line_length": 95,
"avg_line_length": 31.519607843137255,
"alnum_prop": 0.5548989113530327,
"repo_name": "andreasaronsson/kataromannumerals",
"id": "efb26d3dca05b1ebb87c60a3595369863d4f7446",
"size": "3215",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/test/java/nu/aron/kataromannumerals/MainTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "8806"
}
],
"symlink_target": ""
} |
default: builddocker
setup:
go get -u
buildgo:
CGO_ENABLED=0 GOOS=linux go build -ldflags "-s" -a -installsuffix cgo -o main ./main.go
builddocker: buildgo
docker build -t byrnedo/blogsvc .
dev-env:
docker rm -f dev_consul dev_registrator
(cd ./_environments/ && capitan -d up)
run: dev-env
docker run \
-p 8080:80 byrnedo/blogsvc
| {
"content_hash": "444f0c2c41264149a83b51dd9800ab5c",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 88,
"avg_line_length": 18.42105263157895,
"alnum_prop": 0.6971428571428572,
"repo_name": "byrnedo/blogsvc",
"id": "799e53adf778802cf77b71dbd081836674a9dcdf",
"size": "350",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Makefile",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Go",
"bytes": "12613"
},
{
"name": "Makefile",
"bytes": "459"
},
{
"name": "Protocol Buffer",
"bytes": "333"
}
],
"symlink_target": ""
} |
package org.jinstagram.auth.oauth;
import java.io.IOException;
import org.jinstagram.Instagram;
import org.jinstagram.InstagramClient;
import org.jinstagram.auth.InstagramApi;
import org.jinstagram.auth.exceptions.OAuthException;
import org.jinstagram.auth.model.OAuthConfig;
import org.jinstagram.auth.model.OAuthConstants;
import org.jinstagram.auth.model.OAuthRequest;
import org.jinstagram.auth.model.Token;
import org.jinstagram.auth.model.Verifier;
import org.jinstagram.http.Response;
public class InstagramService {
private static final String VERSION = "1.0";
private static final String AUTHORIZATION_CODE = "authorization_code";
private final InstagramApi api;
private final OAuthConfig config;
/**
* Default constructor
*
* @param api OAuth2.0 api information
* @param config OAuth 2.0 configuration param object
*/
public InstagramService(InstagramApi api, OAuthConfig config) {
this.api = api;
this.config = config;
}
/**
* {@inheritDoc}
*/
public Token getAccessToken(Verifier verifier) {
OAuthRequest request = new OAuthRequest(api.getAccessTokenVerb(), api.getAccessTokenEndpoint());
// Add the oauth parameter in the body
request.addBodyParameter(OAuthConstants.CLIENT_ID, config.getApiKey());
request.addBodyParameter(OAuthConstants.CLIENT_SECRET, config.getApiSecret());
request.addBodyParameter(OAuthConstants.GRANT_TYPE, AUTHORIZATION_CODE);
request.addBodyParameter(OAuthConstants.CODE, verifier.getValue());
request.addBodyParameter(OAuthConstants.REDIRECT_URI, config.getCallback());
if (config.hasScope()) {
request.addBodyParameter(OAuthConstants.SCOPE, config.getScope());
}
if (config.getDisplay() != null) {
request.addBodyParameter(OAuthConstants.DISPLAY, config.getDisplay());
}
if (config.getRequestProxy() != null) {
request.setProxy(config.getRequestProxy() );
}
Response response;
try {
response = request.send();
} catch (IOException e) {
throw new OAuthException("Could not get access token", e);
}
return api.getAccessTokenExtractor().extract(response.getBody());
}
/**
* {@inheritDoc}
*/
public Token getRequestToken() {
throw new UnsupportedOperationException(
"Unsupported operation, please use 'getAuthorizationUrl' and redirect your users there");
}
/**
* {@inheritDoc}
*/
public String getVersion() {
return VERSION;
}
/**
* {@inheritDoc}
*/
public void signRequest(Token accessToken, OAuthRequest request) {
request.addQuerystringParameter(OAuthConstants.ACCESS_TOKEN, accessToken.getToken());
}
/**
* {@inheritDoc}
*/
public String getAuthorizationUrl() {
return api.getAuthorizationUrl(config);
}
/**
* Return an Instagram object
*/
public InstagramClient getInstagram(Token accessToken) {
return new Instagram(accessToken);
}
/**
* Return an Instagram object with enforced signed header
*/
@Deprecated
public InstagramClient getSignedHeaderInstagram(Token accessToken, String ipAddress) {
return new Instagram(accessToken.getToken(), config.getApiSecret(), ipAddress);
}
}
| {
"content_hash": "4e702a6e4657106eb315dcd4cadfc6c6",
"timestamp": "",
"source": "github",
"line_count": 114,
"max_line_length": 98,
"avg_line_length": 27.026315789473685,
"alnum_prop": 0.7487828627069133,
"repo_name": "zauberlabs/jInstagram",
"id": "f13d2c55e9ad8a05cf95257d1edfe8c15acce9d2",
"size": "3081",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/main/java/org/jinstagram/auth/oauth/InstagramService.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "554263"
}
],
"symlink_target": ""
} |
permalink: /HiTRACE/tutorial/step_3/
redirect_to: https://ribokit.github.io/HiTRACE/tutorial/step_3/
---
| {
"content_hash": "9e84fe8de34b6417592fd5fa10c4d2bb",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 63,
"avg_line_length": 35,
"alnum_prop": 0.7523809523809524,
"repo_name": "hitrace/hitrace.github.io",
"id": "d2256f14fa3f56d0fba6146fa7f97ab7e30d5698",
"size": "109",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "redirect/hitrace/step_3.md",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "HTML",
"bytes": "13205"
}
],
"symlink_target": ""
} |
package org.redisson.executor.params;
import java.io.Serializable;
/**
*
* @author Nikita Koksharov
*
*/
public class TaskParameters implements Serializable {
private static final long serialVersionUID = -5662511632962297898L;
private String className;
private byte[] classBody;
private byte[] state;
private String requestId;
public TaskParameters() {
}
public TaskParameters(String className, byte[] classBody, byte[] state) {
super();
this.className = className;
this.classBody = classBody;
this.state = state;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public byte[] getClassBody() {
return classBody;
}
public void setClassBody(byte[] classBody) {
this.classBody = classBody;
}
public byte[] getState() {
return state;
}
public void setState(byte[] state) {
this.state = state;
}
public String getRequestId() {
return requestId;
}
public void setRequestId(String requestId) {
this.requestId = requestId;
}
}
| {
"content_hash": "2f48b6017e8276f1a5839667929041c4",
"timestamp": "",
"source": "github",
"line_count": 58,
"max_line_length": 77,
"avg_line_length": 21.29310344827586,
"alnum_prop": 0.617004048582996,
"repo_name": "jackygurui/redisson",
"id": "e1673dbcd16965afd8479d3ad8dbb32984c0a87a",
"size": "1834",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "redisson/src/main/java/org/redisson/executor/params/TaskParameters.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "5826881"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>quarkus-spring-data-jpa-parent</artifactId>
<groupId>io.quarkus</groupId>
<version>999-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>quarkus-spring-data-jpa-deployment</artifactId>
<name>Quarkus - Spring Data JPA - Deployment</name>
<dependencies>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-spring-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-hibernate-orm-panache-deployment</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-spring-di-deployment</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-junit5-internal</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-resteasy-jackson-deployment</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-jdbc-h2-deployment</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<annotationProcessorPaths>
<path>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-extension-processor</artifactId>
<version>${project.version}</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
</plugins>
</build>
</project>
| {
"content_hash": "46a645330443668e15f96f8cdef7650c",
"timestamp": "",
"source": "github",
"line_count": 73,
"max_line_length": 109,
"avg_line_length": 35.49315068493151,
"alnum_prop": 0.5549980702431494,
"repo_name": "quarkusio/quarkus",
"id": "c9d9f16913e7c3a0799e57fa181b315d8d3ec471",
"size": "2591",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "extensions/spring-data-jpa/deployment/pom.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "23342"
},
{
"name": "Batchfile",
"bytes": "13096"
},
{
"name": "CSS",
"bytes": "6685"
},
{
"name": "Dockerfile",
"bytes": "459"
},
{
"name": "FreeMarker",
"bytes": "8106"
},
{
"name": "Groovy",
"bytes": "16133"
},
{
"name": "HTML",
"bytes": "1418749"
},
{
"name": "Java",
"bytes": "38584810"
},
{
"name": "JavaScript",
"bytes": "90960"
},
{
"name": "Kotlin",
"bytes": "704351"
},
{
"name": "Mustache",
"bytes": "13191"
},
{
"name": "Scala",
"bytes": "9756"
},
{
"name": "Shell",
"bytes": "71729"
}
],
"symlink_target": ""
} |
<?php
namespace Symfony\Component\Config\Definition\Builder;
use Symfony\Component\Config\Definition\NodeInterface;
use Symfony\Component\Config\Definition\Exception\InvalidDefinitionException;
/**
* This class provides a fluent interface for defining a node.
*
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
*/
abstract class NodeDefinition implements NodeParentInterface
{
protected $name;
protected $normalization;
protected $validation;
protected $defaultValue;
protected $default = false;
protected $required = false;
protected $deprecationMessage = null;
protected $merge;
protected $allowEmptyValue = true;
protected $nullEquivalent;
protected $trueEquivalent = true;
protected $falseEquivalent = false;
protected $parent;
protected $attributes = array();
/**
* @param string|null $name The name of the node
* @param NodeParentInterface|null $parent The parent
*/
public function __construct($name, NodeParentInterface $parent = null)
{
$this->parent = $parent;
$this->name = $name;
}
/**
* Sets the parent node.
*
* @return $this
*/
public function setParent(NodeParentInterface $parent)
{
$this->parent = $parent;
return $this;
}
/**
* Sets info message.
*
* @param string $info The info text
*
* @return $this
*/
public function info($info)
{
return $this->attribute('info', $info);
}
/**
* Sets example configuration.
*
* @param string|array $example
*
* @return $this
*/
public function example($example)
{
return $this->attribute('example', $example);
}
/**
* Sets an attribute on the node.
*
* @param string $key
* @param mixed $value
*
* @return $this
*/
public function attribute($key, $value)
{
$this->attributes[$key] = $value;
return $this;
}
/**
* Returns the parent node.
*
* @return NodeParentInterface|NodeBuilder|NodeDefinition|ArrayNodeDefinition|VariableNodeDefinition|null The builder of the parent node
*/
public function end()
{
return $this->parent;
}
/**
* Creates the node.
*
* @param bool $forceRootNode Whether to force this node as the root node
*
* @return NodeInterface
*/
public function getNode($forceRootNode = false)
{
if ($forceRootNode) {
$this->parent = null;
}
if (null !== $this->normalization) {
$this->normalization->before = ExprBuilder::buildExpressions($this->normalization->before);
}
if (null !== $this->validation) {
$this->validation->rules = ExprBuilder::buildExpressions($this->validation->rules);
}
$node = $this->createNode();
$node->setAttributes($this->attributes);
return $node;
}
/**
* Sets the default value.
*
* @param mixed $value The default value
*
* @return $this
*/
public function defaultValue($value)
{
$this->default = true;
$this->defaultValue = $value;
return $this;
}
/**
* Sets the node as required.
*
* @return $this
*/
public function isRequired()
{
$this->required = true;
return $this;
}
/**
* Sets the node as deprecated.
*
* You can use %node% and %path% placeholders in your message to display,
* respectively, the node name and its complete path.
*
* @param string $message Deprecation message
*
* @return $this
*/
public function setDeprecated($message = 'The child node "%node%" at path "%path%" is deprecated.')
{
$this->deprecationMessage = $message;
return $this;
}
/**
* Sets the equivalent value used when the node contains null.
*
* @param mixed $value
*
* @return $this
*/
public function treatNullLike($value)
{
$this->nullEquivalent = $value;
return $this;
}
/**
* Sets the equivalent value used when the node contains true.
*
* @param mixed $value
*
* @return $this
*/
public function treatTrueLike($value)
{
$this->trueEquivalent = $value;
return $this;
}
/**
* Sets the equivalent value used when the node contains false.
*
* @param mixed $value
*
* @return $this
*/
public function treatFalseLike($value)
{
$this->falseEquivalent = $value;
return $this;
}
/**
* Sets null as the default value.
*
* @return $this
*/
public function defaultNull()
{
return $this->defaultValue(null);
}
/**
* Sets true as the default value.
*
* @return $this
*/
public function defaultTrue()
{
return $this->defaultValue(true);
}
/**
* Sets false as the default value.
*
* @return $this
*/
public function defaultFalse()
{
return $this->defaultValue(false);
}
/**
* Sets an expression to run before the normalization.
*
* @return ExprBuilder
*/
public function beforeNormalization()
{
return $this->normalization()->before();
}
/**
* Denies the node value being empty.
*
* @return $this
*/
public function cannotBeEmpty()
{
$this->allowEmptyValue = false;
return $this;
}
/**
* Sets an expression to run for the validation.
*
* The expression receives the value of the node and must return it. It can
* modify it.
* An exception should be thrown when the node is not valid.
*
* @return ExprBuilder
*/
public function validate()
{
return $this->validation()->rule();
}
/**
* Sets whether the node can be overwritten.
*
* @param bool $deny Whether the overwriting is forbidden or not
*
* @return $this
*/
public function cannotBeOverwritten($deny = true)
{
$this->merge()->denyOverwrite($deny);
return $this;
}
/**
* Gets the builder for validation rules.
*
* @return ValidationBuilder
*/
protected function validation()
{
if (null === $this->validation) {
$this->validation = new ValidationBuilder($this);
}
return $this->validation;
}
/**
* Gets the builder for merging rules.
*
* @return MergeBuilder
*/
protected function merge()
{
if (null === $this->merge) {
$this->merge = new MergeBuilder($this);
}
return $this->merge;
}
/**
* Gets the builder for normalization rules.
*
* @return NormalizationBuilder
*/
protected function normalization()
{
if (null === $this->normalization) {
$this->normalization = new NormalizationBuilder($this);
}
return $this->normalization;
}
/**
* Instantiate and configure the node according to this definition.
*
* @return NodeInterface $node The node instance
*
* @throws InvalidDefinitionException When the definition is invalid
*/
abstract protected function createNode();
}
| {
"content_hash": "c010f5fd3def849ff5ea105ecffc3442",
"timestamp": "",
"source": "github",
"line_count": 346,
"max_line_length": 140,
"avg_line_length": 21.63583815028902,
"alnum_prop": 0.5653219342773177,
"repo_name": "cavo789/marknotes",
"id": "7dcfd5164d86e9178e9404cf43fdf5b3cf4ae7ef",
"size": "7715",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "src/libs/symfony/config/Definition/Builder/NodeDefinition.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "45596"
},
{
"name": "C",
"bytes": "8656"
},
{
"name": "CSS",
"bytes": "611146"
},
{
"name": "Dockerfile",
"bytes": "315"
},
{
"name": "HTML",
"bytes": "86141"
},
{
"name": "Hack",
"bytes": "18933"
},
{
"name": "JavaScript",
"bytes": "6201160"
},
{
"name": "M4",
"bytes": "2250"
},
{
"name": "PHP",
"bytes": "11092049"
},
{
"name": "SCSS",
"bytes": "65612"
},
{
"name": "Shell",
"bytes": "231"
},
{
"name": "VBA",
"bytes": "45352"
}
],
"symlink_target": ""
} |
<?php
namespace Magento\Quote\Model\ResourceModel\Quote\Address;
use Magento\Framework\Model\ResourceModel\Db\VersionControl\AbstractDb;
/**
* Quote address item resource model
*
* @author Magento Core Team <core@magentocommerce.com>
*/
class Item extends AbstractDb
{
/**
* Main table and field initialization
*
* @return void
*/
protected function _construct()
{
$this->_init('quote_address_item', 'address_item_id');
}
}
| {
"content_hash": "5d0051e878cc303b576395e2309993c3",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 71,
"avg_line_length": 20.869565217391305,
"alnum_prop": 0.6645833333333333,
"repo_name": "tarikgwa/test",
"id": "0d3a2817c217c40c80caa454fd1ab6b919d777d2",
"size": "578",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "html/app/code/Magento/Quote/Model/ResourceModel/Quote/Address/Item.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "26588"
},
{
"name": "CSS",
"bytes": "4874492"
},
{
"name": "HTML",
"bytes": "8635167"
},
{
"name": "JavaScript",
"bytes": "6810903"
},
{
"name": "PHP",
"bytes": "55645559"
},
{
"name": "Perl",
"bytes": "7938"
},
{
"name": "Shell",
"bytes": "4505"
},
{
"name": "XSLT",
"bytes": "19889"
}
],
"symlink_target": ""
} |
<?php
require_once __DIR__.'/ECommerceKernel.php';
use Symfony\Bundle\FrameworkBundle\Cache\Cache;
use Symfony\Component\HttpFoundation\Request;
class ECommerceCache extends Cache
{
public function handleAndSend()
{
return $this->handle(new Request)->send();
}
}
| {
"content_hash": "9d9750c6a7cad2efdc728a02206a31eb",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 50,
"avg_line_length": 20.428571428571427,
"alnum_prop": 0.7132867132867133,
"repo_name": "docteurklein/Symfony2-e-commerce",
"id": "dc2efbc33230ac4ce1295de928e9ca85d345512e",
"size": "286",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "eCommerce/ECommerceCache.php",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "105832"
}
],
"symlink_target": ""
} |
module Google
module Apis
module FirebasestorageV1beta
# Version of the google-apis-firebasestorage_v1beta gem
GEM_VERSION = "0.16.0"
# Version of the code generator used to generate this client
GENERATOR_VERSION = "0.11.0"
# Revision of the discovery document this client was generated from
REVISION = "20220927"
end
end
end
| {
"content_hash": "1d3b10a1dec4daf441f03cc6546f90cf",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 73,
"avg_line_length": 26.857142857142858,
"alnum_prop": 0.6888297872340425,
"repo_name": "googleapis/google-api-ruby-client",
"id": "6be011e8f2fb84adc39688447ad7c4ca10d1878b",
"size": "952",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "generated/google-apis-firebasestorage_v1beta/lib/google/apis/firebasestorage_v1beta/gem_version.rb",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Ruby",
"bytes": "198322756"
},
{
"name": "Shell",
"bytes": "19549"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>{% block title %} {% endblock %}</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- Le styles -->
<link href="/static/css/bootstrap.css" rel="stylesheet">
<style type="text/css">
body {
padding-top: 60px;
padding-bottom: 40px;
}
.sidebar-nav {
padding: 9px 0;
}
</style>
<link href="../assets/css/bootstrap-responsive.css" rel="stylesheet">
<!-- Le HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="</SCRIPT'">http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<div class="navbar navbar-fixed-top">
<div class="navbar-inner">
<div class="container-fluid">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="brand" href="#">图书管理</a>
<div class="btn-group pull-right">
<a class="btn dropdown-toggle" data-toggle="dropdown" href="#">
<i class="icon-user"></i> Username
<span class="caret"></span>
</a>
<ul class="dropdown-menu">
<li><a href="#">个人资料</a></li>
<li class="divider"></li>
<li><a href="#">退出系统</a></li>
</ul>
</div>
<div class="nav-collapse">
<ul class="nav">
<li class="active"><a href="#">首页</a></li>
<li><a href="#about">图书管理</a></li>
<li><a href="#about">关于</a></li>
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
</div>
<div class="container-fluid">
<div class="row-fluid">
<div class="span2">
<div class="well sidebar-nav">
<ul class="nav nav-list">
<li class="nav-header">图书管理</li>
<li class="active"><a href="#">图书列表</a></li>
<li><a href="#">我的图书</a></li>
<li><a href="#">请求处理</a></li>
</ul>
</div><!--/.well -->
</div><!--/span-->
<div class="span10">
{% block content %}
{% endblock %}
</div><!--/span-->
</div><!--/row-->
<hr>
<footer>
<p>© Company 2012</p>
</footer>
</div><!--/.fluid-container-->
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="/static/js/jquery.js"></script>
<script src="/static/js/bootstrap-transition.js"></script>
<script src="/static/js/bootstrap-alert.js"></script>
<script src="/static/js/bootstrap-modal.js"></script>
<script src="/static/js/bootstrap-dropdown.js"></script>
<script src="/static/js/bootstrap-scrollspy.js"></script>
<script src="/static/js/bootstrap-tab.js"></script>
<script src="/static/js/bootstrap-tooltip.js"></script>
<script src="/static/js/bootstrap-popover.js"></script>
<script src="/static/js/bootstrap-button.js"></script>
<script src="/static/js/bootstrap-collapse.js"></script>
<script src="/static/js/bootstrap-carousel.js"></script>
<script src="/static/js/bootstrap-typeahead.js"></script>
</body>
</html> | {
"content_hash": "e1430adefeee009a3017441af5a96350",
"timestamp": "",
"source": "github",
"line_count": 107,
"max_line_length": 85,
"avg_line_length": 28.009345794392523,
"alnum_prop": 0.6126126126126126,
"repo_name": "yokiwhh/bookLab7",
"id": "2ab9d05957cc7dff0268001c01e330a541f9d8a6",
"size": "3069",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "bookapp/templates/base.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "10670"
},
{
"name": "Python",
"bytes": "18373"
}
],
"symlink_target": ""
} |
package main
import (
"context"
"errors"
"io"
"log"
"os"
"time"
"google.golang.org/api/iterator"
spanner "cloud.google.com/go/spanner/apiv1"
spannerpb "google.golang.org/genproto/googleapis/spanner/v1"
)
const (
database = "projects/grpc-prober-testing/instances/test-instance/databases/test-db"
table = "users"
testUsername = "test_username"
)
func createClient() *spanner.Client {
ctx := context.Background()
client, _ := spanner.NewClient(ctx)
if client == nil {
log.Fatal("Fail to create the client.")
os.Exit(1)
}
return client
}
func sessionManagementProber(client *spanner.Client, metrics map[string]int64) error {
ctx := context.Background()
reqCreate := &spannerpb.CreateSessionRequest{
Database: database,
}
start := time.Now()
session, err := client.CreateSession(ctx, reqCreate)
if err != nil {
return err
}
if session == nil {
return errors.New("failded to create a new session")
}
metrics["create_session_latency_ms"] = int64(time.Now().Sub(start) / time.Millisecond)
// DeleteSession
defer func() {
start = time.Now()
reqDelete := &spannerpb.DeleteSessionRequest{
Name: session.Name,
}
client.DeleteSession(ctx, reqDelete)
metrics["delete_session_latency_ms"] = int64(time.Now().Sub(start) / time.Millisecond)
}()
// GetSession
reqGet := &spannerpb.GetSessionRequest{
Name: session.Name,
}
start = time.Now()
respGet, err := client.GetSession(ctx, reqGet)
if err != nil {
return err
}
if reqGet == nil || respGet.Name != session.Name {
return errors.New("fail to get the session")
}
metrics["get_session_latency_ms"] = int64(time.Now().Sub(start) / time.Millisecond)
// ListSessions
reqList := &spannerpb.ListSessionsRequest{
Database: database,
}
start = time.Now()
it := client.ListSessions(ctx, reqList)
inList := false
for {
resp, err := it.Next()
if err == iterator.Done {
break
}
if err != nil {
return err
}
if resp.Name == session.Name {
inList = true
break
}
}
metrics["list_sessions_latency_ms"] = int64(time.Now().Sub(start) / time.Millisecond)
if !inList {
return errors.New("list sessions failed")
}
return nil
}
func executeSqlProber(client *spanner.Client, metrics map[string]int64) error {
ctx := context.Background()
session := createSession(client)
defer deleteSession(client, session)
reqSql := &spannerpb.ExecuteSqlRequest{
Sql: "select * FROM " + table,
Session: session.Name,
}
// ExecuteSql
start := time.Now()
respSql, err1 := client.ExecuteSql(ctx, reqSql)
if err1 != nil {
return err1
}
if respSql == nil || len(respSql.Rows) != 1 || respSql.Rows[0].Values[0].GetStringValue() != testUsername {
return errors.New("execute sql failed")
}
metrics["execute_sql_latency_ms"] = int64(time.Now().Sub(start) / time.Millisecond)
// ExecuteStreamingSql
start = time.Now()
stream, err2 := client.ExecuteStreamingSql(ctx, reqSql)
if err2 != nil {
return err2
}
for {
resp, err := stream.Recv()
if err == io.EOF {
break
}
if err != nil {
return err
}
if resp == nil || resp.Values[0].GetStringValue() != testUsername {
return errors.New("execute streaming sql failed")
}
}
metrics["execute_streaming_sql_latency_ms"] = int64(time.Now().Sub(start) / time.Millisecond)
return nil
}
func readProber(client *spanner.Client, metrics map[string]int64) error {
ctx := context.Background()
session := createSession(client)
defer deleteSession(client, session)
reqRead := &spannerpb.ReadRequest{
Session: session.Name,
Table: table,
KeySet: &spannerpb.KeySet{
All: true,
},
Columns: []string{"username", "firstname", "lastname"},
}
// Read
start := time.Now()
respRead, err1 := client.Read(ctx, reqRead)
if err1 != nil {
return err1
}
if respRead == nil || len(respRead.Rows) != 1 || respRead.Rows[0].Values[0].GetStringValue() != testUsername {
return errors.New("execute read failed")
}
metrics["read_latency_ms"] = int64(time.Now().Sub(start) / time.Millisecond)
// StreamingRead
start = time.Now()
stream, err2 := client.StreamingRead(ctx, reqRead)
if err2 != nil {
return err2
}
for {
resp, err := stream.Recv()
if err == io.EOF {
break
}
if err != nil {
return err
}
if resp == nil || resp.Values[0].GetStringValue() != testUsername {
return errors.New("streaming read failed")
}
}
metrics["streaming_read_latency_ms"] = int64(time.Now().Sub(start) / time.Millisecond)
return nil
}
func transactionProber(client *spanner.Client, metrics map[string]int64) error {
ctx := context.Background()
session := createSession(client)
reqBegin := &spannerpb.BeginTransactionRequest{
Session: session.Name,
Options: &spannerpb.TransactionOptions{
Mode: &spannerpb.TransactionOptions_ReadWrite_{
ReadWrite: &spannerpb.TransactionOptions_ReadWrite{},
},
},
}
// BeginTransaction
start := time.Now()
txn, err1 := client.BeginTransaction(ctx, reqBegin)
if err1 != nil {
return err1
}
metrics["begin_transaction_latency_ms"] = int64(time.Now().Sub(start) / time.Millisecond)
// Commit
reqCommit := &spannerpb.CommitRequest{
Session: session.Name,
Transaction: &spannerpb.CommitRequest_TransactionId{
TransactionId: txn.Id,
},
}
start = time.Now()
_, err2 := client.Commit(ctx, reqCommit)
if err2 != nil {
return err2
}
metrics["commit_latency_ms"] = int64(time.Now().Sub(start) / time.Millisecond)
// Rollback
txn, err1 = client.BeginTransaction(ctx, reqBegin)
if err1 != nil {
return err1
}
reqRollback := &spannerpb.RollbackRequest{
Session: session.Name,
TransactionId: txn.Id,
}
start = time.Now()
err2 = client.Rollback(ctx, reqRollback)
if err2 != nil {
return err2
}
metrics["rollback_latency_ms"] = int64(time.Now().Sub(start) / time.Millisecond)
reqDelete := &spannerpb.DeleteSessionRequest{
Name: session.Name,
}
client.DeleteSession(ctx, reqDelete)
return nil
}
func partitionProber(client *spanner.Client, metrics map[string]int64) error {
ctx := context.Background()
session := createSession(client)
defer deleteSession(client, session)
selector := &spannerpb.TransactionSelector{
Selector: &spannerpb.TransactionSelector_Begin{
Begin: &spannerpb.TransactionOptions{
Mode: &spannerpb.TransactionOptions_ReadOnly_{
ReadOnly: &spannerpb.TransactionOptions_ReadOnly{},
},
},
},
}
// PartitionQuery
reqQuery := &spannerpb.PartitionQueryRequest{
Session: session.Name,
Sql: "select * FROM " + table,
Transaction: selector,
}
start := time.Now()
_, err := client.PartitionQuery(ctx, reqQuery)
if err != nil {
return err
}
metrics["partition_query_latency_ms"] = int64(time.Now().Sub(start) / time.Millisecond)
// PartitionRead
reqRead := &spannerpb.PartitionReadRequest{
Session: session.Name,
Table: table,
KeySet: &spannerpb.KeySet{
All: true,
},
Columns: []string{"username", "firstname", "lastname"},
Transaction: selector,
}
start = time.Now()
_, err = client.PartitionRead(ctx, reqRead)
if err != nil {
return err
}
metrics["partition_read_latency_ms"] = int64(time.Now().Sub(start) / time.Millisecond)
return nil
}
func createSession(client *spanner.Client) *spannerpb.Session {
ctx := context.Background()
reqCreate := &spannerpb.CreateSessionRequest{
Database: database,
}
session, err := client.CreateSession(ctx, reqCreate)
if err != nil {
log.Fatal(err.Error())
return nil
}
if session == nil {
log.Fatal("Failded to create a new session.")
return nil
}
return session
}
func deleteSession(client *spanner.Client, session *spannerpb.Session) {
if client == nil {
return
}
ctx := context.Background()
reqDelete := &spannerpb.DeleteSessionRequest{
Name: session.Name,
}
client.DeleteSession(ctx, reqDelete)
}
| {
"content_hash": "7157003cbe6c466d1f5b122326232f12",
"timestamp": "",
"source": "github",
"line_count": 318,
"max_line_length": 111,
"avg_line_length": 24.540880503144653,
"alnum_prop": 0.6863147104049205,
"repo_name": "GoogleCloudPlatform/grpc-gcp-go",
"id": "055ea4f726f84400b35424183e23c29a8e52bb99",
"size": "8403",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "cloudprober/spannerprobers.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "446"
},
{
"name": "Go",
"bytes": "159885"
},
{
"name": "Shell",
"bytes": "644"
}
],
"symlink_target": ""
} |
@implementation BQModel
@end
| {
"content_hash": "0dda9a13c5670323695929db6f810f21",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 23,
"avg_line_length": 7.75,
"alnum_prop": 0.7741935483870968,
"repo_name": "zhangzhujuan/TableViewCollectionView",
"id": "ddace728fea489b3372b049152f45a20feaf0170",
"size": "181",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "DevelopFramework/DevelopFramework/Classes/Src/firstExample/Model/BQModel.m",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "591347"
}
],
"symlink_target": ""
} |
title: "State Backends"
sub-nav-group: streaming
sub-nav-pos: 2
sub-nav-parent: fault_tolerance
---
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
Programs written in the [Data Stream API](index.html) often hold state in various forms:
- Windows gather elements or aggregates until they are triggered
- Transformation functions may use the key/value state interface to store values
- Transformation functions may implement the `Checkpointed` interface to make their local variables fault tolerant
See also [Working with State](state.html) in the streaming API guide.
When checkpointing is activated, such state is persisted upon checkpoints to guard against data loss and recover consistently.
How the state is represented internally, and how and where it is persisted upon checkpoints depends on the
chosen **State Backend**.
* ToC
{:toc}
## Available State Backends
Out of the box, Flink bundles these state backends:
- *MemoryStateBacked*
- *FsStateBackend*
- *RocksDBStateBackend*
If nothing else is configured, the system will use the MemoryStateBacked.
### The MemoryStateBackend
The *MemoryStateBacked* holds data internally as objects on the Java heap. Key/value state and window operators hold hash tables
that store the values, triggers, etc.
Upon checkpoints, this state backend will snapshot the state and send it as part of the checkpoint acknowledgement messages to the
JobManager (master), which stores it on its heap as well.
Limitations of the MemoryStateBackend:
- The size of each individual state is by default limited to 5 MB. This value can be increased in the constructor of the MemoryStateBackend.
- Irrespective of the configured maximal state size, the state cannot be larger than the akka frame size (see [Configuration]({{ site.baseurl }}/setup/config.html)).
- The aggregate state must fit into the JobManager memory.
The MemoryStateBackend is encouraged for:
- Local development and debugging
- Jobs that do hold little state, such as jobs that consist only of record-at-a-time functions (Map, FlatMap, Filter, ...). The Kafka Consumer requires very little state.
### The FsStateBackend
The *FsStateBackend* is configured with a file system URL (type, address, path), such as for example "hdfs://namenode:40010/flink/checkpoints" or "file:///data/flink/checkpoints".
The FsStateBackend holds in-flight data in the TaskManager's memory. Upon checkpointing, it writes state snapshots into files in the configured file system and directory. Minimal metadata is stored in the JobManager's memory (or, in high-availability mode, in the metadata checkpoint).
The FsStateBackend is encouraged for:
- Jobs with large state, long windows, large key/value states.
- All high-availability setups.
### The RocksDBStateBackend
The *RocksDBStateBackend* is configured with a file system URL (type, address, path), such as for example "hdfs://namenode:40010/flink/checkpoints" or "file:///data/flink/checkpoints".
The RocksDBStateBackend holds in-flight data in a [RocksDB](http://rocksdb.org) data base
that is (per default) stored in the TaskManager data directories. Upon checkpointing, the whole
RocksDB data base will be checkpointed into the configured file system and directory. Minimal
metadata is stored in the JobManager's memory (or, in high-availability mode, in the metadata checkpoint).
The RocksDBStateBackend is encouraged for:
- Jobs with very large state, long windows, large key/value states.
- All high-availability setups.
Note that the amount of state that you can keep is only limited by the amount of disc space available.
This allows keeping very large state, compared to the FsStateBackend that keeps state in memory.
This also means, however, that the maximum throughput that can be achieved will be lower with
this state backend.
**NOTE:** To use the RocksDBStateBackend you also have to add the correct maven dependency to your
project:
{% highlight xml %}
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-statebackend-rocksdb{{ site.scala_version_suffix }}</artifactId>
<version>{{site.version }}</version>
</dependency>
{% endhighlight %}
The backend is currently not part of the binary distribution. See
[here]({{ site.baseurl}}/apis/cluster_execution.html#linking-with-modules-not-contained-in-the-binary-distribution)
for an explanation of how to include it for cluster execution.
## Configuring a State Backend
State backends can be configured per job. In addition, you can define a default state backend to be used when the
job does not explicitly define a state backend.
### Setting the Per-job State Backend
The per-job state backend is set on the `StreamExecutionEnvironment` of the job, as shown in the example below:
<div class="codetabs" markdown="1">
<div data-lang="java" markdown="1">
{% highlight java %}
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setStateBackend(new FsStateBackend("hdfs://namenode:40010/flink/checkpoints"));
{% endhighlight %}
</div>
<div data-lang="scala" markdown="1">
{% highlight scala %}
val env = StreamExecutionEnvironment.getExecutionEnvironment()
env.setStateBackend(new FsStateBackend("hdfs://namenode:40010/flink/checkpoints"))
{% endhighlight %}
</div>
</div>
### Setting Default State Backend
A default state backend can be configured in the `flink-conf.yaml`, using the configuration key `state.backend`.
Possible values for the config entry are *jobmanager* (MemoryStateBackend), *filesystem* (FsStateBackend), or the fully qualified class
name of the class that implements the state backend factory [FsStateBackendFactory](https://github.com/apache/flink/blob/master/flink-runtime/src/main/java/org/apache/flink/runtime/state/filesystem/FsStateBackendFactory.java).
In the case where the default state backend is set to *filesystem*, the entry `state.backend.fs.checkpointdir` defines the directory where the checkpoint data will be stored.
A sample section in the configuration file could look as follows:
~~~
# The backend that will be used to store operator state checkpoints
state.backend: filesystem
# Directory for storing checkpoints
state.backend.fs.checkpointdir: hdfs://namenode:40010/flink/checkpoints
~~~
| {
"content_hash": "7c0b54a22ef98bb2823d69291e823249",
"timestamp": "",
"source": "github",
"line_count": 162,
"max_line_length": 285,
"avg_line_length": 43.04938271604938,
"alnum_prop": 0.7847720103240607,
"repo_name": "aspoman/flink-china-doc",
"id": "f9471dd9e0d3a8db7f863155a5d9abbe671d625e",
"size": "6978",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "apis/streaming/state_backends.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "2194"
},
{
"name": "CSS",
"bytes": "11793"
},
{
"name": "HTML",
"bytes": "21333"
},
{
"name": "JavaScript",
"bytes": "4635"
},
{
"name": "Python",
"bytes": "2413"
},
{
"name": "Ruby",
"bytes": "11541"
},
{
"name": "Shell",
"bytes": "5537"
}
],
"symlink_target": ""
} |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.sql;
import com.facebook.presto.sql.planner.ExpressionDeterminismEvaluator;
import com.facebook.presto.sql.tree.ComparisonExpression;
import com.facebook.presto.sql.tree.DereferenceExpression;
import com.facebook.presto.sql.tree.Expression;
import com.facebook.presto.sql.tree.ExpressionRewriter;
import com.facebook.presto.sql.tree.ExpressionTreeRewriter;
import com.facebook.presto.sql.tree.FunctionCall;
import com.facebook.presto.sql.tree.GroupingElement;
import com.facebook.presto.sql.tree.Identifier;
import com.facebook.presto.sql.tree.LambdaExpression;
import com.facebook.presto.sql.tree.LogicalBinaryExpression;
import com.facebook.presto.sql.tree.NotExpression;
import com.facebook.presto.sql.tree.SimpleGroupBy;
import com.facebook.presto.sql.tree.SingleColumn;
import com.facebook.presto.sql.tree.SortItem;
import com.facebook.presto.sql.tree.SymbolReference;
import com.google.common.collect.ImmutableList;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Queue;
import java.util.Set;
import java.util.function.Predicate;
import static com.facebook.presto.sql.tree.BooleanLiteral.FALSE_LITERAL;
import static com.facebook.presto.sql.tree.BooleanLiteral.TRUE_LITERAL;
import static com.facebook.presto.sql.tree.ComparisonExpression.Operator.IS_DISTINCT_FROM;
import static java.util.Objects.requireNonNull;
import static java.util.stream.Collectors.toList;
@Deprecated
public final class ExpressionUtils
{
private ExpressionUtils() {}
public static List<Expression> extractConjuncts(Expression expression)
{
return extractPredicates(LogicalBinaryExpression.Operator.AND, expression);
}
public static List<Expression> extractDisjuncts(Expression expression)
{
return extractPredicates(LogicalBinaryExpression.Operator.OR, expression);
}
public static List<Expression> extractPredicates(LogicalBinaryExpression expression)
{
return extractPredicates(expression.getOperator(), expression);
}
public static List<Expression> extractPredicates(LogicalBinaryExpression.Operator operator, Expression expression)
{
if (expression instanceof LogicalBinaryExpression && ((LogicalBinaryExpression) expression).getOperator() == operator) {
LogicalBinaryExpression logicalBinaryExpression = (LogicalBinaryExpression) expression;
return ImmutableList.<Expression>builder()
.addAll(extractPredicates(operator, logicalBinaryExpression.getLeft()))
.addAll(extractPredicates(operator, logicalBinaryExpression.getRight()))
.build();
}
return ImmutableList.of(expression);
}
public static Expression and(Expression... expressions)
{
return and(Arrays.asList(expressions));
}
public static Expression and(Collection<Expression> expressions)
{
return binaryExpression(LogicalBinaryExpression.Operator.AND, expressions);
}
public static Expression or(Expression... expressions)
{
return or(Arrays.asList(expressions));
}
public static Expression or(Collection<Expression> expressions)
{
return binaryExpression(LogicalBinaryExpression.Operator.OR, expressions);
}
public static Expression binaryExpression(LogicalBinaryExpression.Operator operator, Collection<Expression> expressions)
{
requireNonNull(operator, "operator is null");
requireNonNull(expressions, "expressions is null");
if (expressions.isEmpty()) {
switch (operator) {
case AND:
return TRUE_LITERAL;
case OR:
return FALSE_LITERAL;
default:
throw new IllegalArgumentException("Unsupported LogicalBinaryExpression operator");
}
}
// Build balanced tree for efficient recursive processing that
// preserves the evaluation order of the input expressions.
//
// The tree is built bottom up by combining pairs of elements into
// binary AND expressions.
//
// Example:
//
// Initial state:
// a b c d e
//
// First iteration:
//
// /\ /\ e
// a b c d
//
// Second iteration:
//
// / \ e
// /\ /\
// a b c d
//
//
// Last iteration:
//
// / \
// / \ e
// /\ /\
// a b c d
Queue<Expression> queue = new ArrayDeque<>(expressions);
while (queue.size() > 1) {
Queue<Expression> buffer = new ArrayDeque<>();
// combine pairs of elements
while (queue.size() >= 2) {
buffer.add(new LogicalBinaryExpression(operator, queue.remove(), queue.remove()));
}
// if there's and odd number of elements, just append the last one
if (!queue.isEmpty()) {
buffer.add(queue.remove());
}
// continue processing the pairs that were just built
queue = buffer;
}
return queue.remove();
}
public static Expression combinePredicates(LogicalBinaryExpression.Operator operator, Expression... expressions)
{
return combinePredicates(operator, Arrays.asList(expressions));
}
public static Expression combinePredicates(LogicalBinaryExpression.Operator operator, Collection<Expression> expressions)
{
if (operator == LogicalBinaryExpression.Operator.AND) {
return combineConjuncts(expressions);
}
return combineDisjuncts(expressions);
}
public static Expression combineConjuncts(Expression... expressions)
{
return combineConjuncts(Arrays.asList(expressions));
}
public static Expression combineConjuncts(Collection<Expression> expressions)
{
requireNonNull(expressions, "expressions is null");
List<Expression> conjuncts = expressions.stream()
.flatMap(e -> ExpressionUtils.extractConjuncts(e).stream())
.filter(e -> !e.equals(TRUE_LITERAL))
.collect(toList());
conjuncts = removeDuplicates(conjuncts);
if (conjuncts.contains(FALSE_LITERAL)) {
return FALSE_LITERAL;
}
return and(conjuncts);
}
public static Expression combineDisjuncts(Collection<Expression> expressions)
{
return combineDisjunctsWithDefault(expressions, FALSE_LITERAL);
}
public static Expression combineDisjunctsWithDefault(Collection<Expression> expressions, Expression emptyDefault)
{
requireNonNull(expressions, "expressions is null");
List<Expression> disjuncts = expressions.stream()
.flatMap(e -> ExpressionUtils.extractDisjuncts(e).stream())
.filter(e -> !e.equals(FALSE_LITERAL))
.collect(toList());
disjuncts = removeDuplicates(disjuncts);
if (disjuncts.contains(TRUE_LITERAL)) {
return TRUE_LITERAL;
}
return disjuncts.isEmpty() ? emptyDefault : or(disjuncts);
}
public static Expression filterConjuncts(Expression expression, Predicate<Expression> predicate)
{
List<Expression> conjuncts = extractConjuncts(expression).stream()
.filter(predicate)
.collect(toList());
return combineConjuncts(conjuncts);
}
/**
* Removes duplicate deterministic expressions. Preserves the relative order
* of the expressions in the list.
*/
private static List<Expression> removeDuplicates(List<Expression> expressions)
{
Set<Expression> seen = new HashSet<>();
ImmutableList.Builder<Expression> result = ImmutableList.builder();
for (Expression expression : expressions) {
if (!ExpressionDeterminismEvaluator.isDeterministic(expression)) {
result.add(expression);
}
else if (!seen.contains(expression)) {
result.add(expression);
seen.add(expression);
}
}
return result.build();
}
public static Expression normalize(Expression expression)
{
if (expression instanceof NotExpression) {
NotExpression not = (NotExpression) expression;
if (not.getValue() instanceof ComparisonExpression && ((ComparisonExpression) not.getValue()).getOperator() != IS_DISTINCT_FROM) {
ComparisonExpression comparison = (ComparisonExpression) not.getValue();
return new ComparisonExpression(comparison.getOperator().negate(), comparison.getLeft(), comparison.getRight());
}
if (not.getValue() instanceof NotExpression) {
return normalize(((NotExpression) not.getValue()).getValue());
}
}
return expression;
}
public static Expression rewriteIdentifiersToSymbolReferences(Expression expression)
{
return ExpressionTreeRewriter.rewriteWith(new ExpressionRewriter<Void>()
{
@Override
public Expression rewriteIdentifier(Identifier node, Void context, ExpressionTreeRewriter<Void> treeRewriter)
{
return new SymbolReference(node.getValue());
}
@Override
public Expression rewriteLambdaExpression(LambdaExpression node, Void context, ExpressionTreeRewriter<Void> treeRewriter)
{
return new LambdaExpression(node.getArguments(), treeRewriter.rewrite(node.getBody(), context));
}
}, expression);
}
public static GroupingElement removeGroupingElementPrefix(GroupingElement groupingElement, Optional<Identifier> removablePrefix)
{
if (!removablePrefix.isPresent()) {
return groupingElement;
}
if (groupingElement instanceof SimpleGroupBy) {
boolean prefixRemoved = false;
ImmutableList.Builder<Expression> rewrittenColumns = ImmutableList.builder();
for (Expression column : groupingElement.getExpressions()) {
Expression processedColumn = removeExpressionPrefix(column, removablePrefix);
if (processedColumn != column) {
prefixRemoved = true;
}
rewrittenColumns.add(processedColumn);
}
if (prefixRemoved) {
return new SimpleGroupBy(rewrittenColumns.build());
}
}
return groupingElement;
}
public static SortItem removeSortItemPrefix(SortItem sortItem, Optional<Identifier> removablePrefix)
{
if (!removablePrefix.isPresent()) {
return sortItem;
}
Expression processedExpression = removeExpressionPrefix(sortItem.getSortKey(), removablePrefix);
if (processedExpression != sortItem.getSortKey()) {
return new SortItem(processedExpression, sortItem.getOrdering(), sortItem.getNullOrdering());
}
return sortItem;
}
public static SingleColumn removeSingleColumnPrefix(SingleColumn singleColumn, Optional<Identifier> removablePrefix)
{
if (!removablePrefix.isPresent()) {
return singleColumn;
}
Expression processedExpression = removeExpressionPrefix(singleColumn.getExpression(), removablePrefix);
if (processedExpression != singleColumn.getExpression()) {
return new SingleColumn(removeExpressionPrefix(singleColumn.getExpression(), removablePrefix), singleColumn.getAlias());
}
return singleColumn;
}
public static Expression removeExpressionPrefix(Expression expression, Optional<Identifier> removablePrefix)
{
if (!removablePrefix.isPresent()) {
return expression;
}
if (expression instanceof DereferenceExpression) {
return removeDereferenceExpressionElementPrefix((DereferenceExpression) expression, removablePrefix);
}
if (expression instanceof FunctionCall) {
return removeFunctionCallPrefix((FunctionCall) expression, removablePrefix);
}
return expression;
}
private static Expression removeDereferenceExpressionElementPrefix(DereferenceExpression dereferenceExpression, Optional<Identifier> removablePrefix)
{
if (removablePrefix.isPresent() && removablePrefix.get().equals(dereferenceExpression.getBase())) {
return dereferenceExpression.getField();
}
return dereferenceExpression;
}
private static FunctionCall removeFunctionCallPrefix(FunctionCall functionCall, Optional<Identifier> removablePrefix)
{
if (!removablePrefix.isPresent()) {
return functionCall;
}
boolean prefixRemoved = false;
ImmutableList.Builder<Expression> rewrittenArguments = ImmutableList.builder();
for (Expression argument : functionCall.getArguments()) {
Expression processedArgument = removeExpressionPrefix(argument, removablePrefix);
if (processedArgument != argument) {
prefixRemoved = true;
}
rewrittenArguments.add(removeExpressionPrefix(argument, removablePrefix));
}
if (prefixRemoved) {
return new FunctionCall(
functionCall.getName(),
functionCall.getWindow(),
functionCall.getFilter(),
functionCall.getOrderBy(),
functionCall.isDistinct(),
functionCall.isIgnoreNulls(),
rewrittenArguments.build());
}
return functionCall;
}
}
| {
"content_hash": "4291a3944820ce0c179580a70075efa6",
"timestamp": "",
"source": "github",
"line_count": 388,
"max_line_length": 153,
"avg_line_length": 37.53092783505155,
"alnum_prop": 0.6567092432358193,
"repo_name": "facebook/presto",
"id": "c34b870be12f84b9dc556f5efba405e2c635a8d3",
"size": "14562",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "presto-main/src/main/java/com/facebook/presto/sql/ExpressionUtils.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "23084"
},
{
"name": "HTML",
"bytes": "65534"
},
{
"name": "Java",
"bytes": "15096490"
},
{
"name": "JavaScript",
"bytes": "4863"
},
{
"name": "Makefile",
"bytes": "6819"
},
{
"name": "PLSQL",
"bytes": "6538"
},
{
"name": "Python",
"bytes": "4479"
},
{
"name": "SQLPL",
"bytes": "6363"
},
{
"name": "Shell",
"bytes": "9520"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?><document>
<properties>
<author email="tom@infoether.com">Tom Copeland</author>
<title>Ruleset: Naming</title>
</properties>
<body>
<section name="Naming">
The Naming Ruleset contains rules regarding preferred usage of names and identifiers.
<subsection name="ShortVariable">
<p>Since: PMD 0.3</p>
<p>
Fields, local variables, or parameter names that are very short are not helpful to the reader.
</p>
<source>
//VariableDeclaratorId[string-length(@Image) < 3]
[not(ancestor::ForInit)]
[not(../../VariableDeclarator and ../../../LocalVariableDeclaration and ../../../../ForStatement)]
[not((ancestor::FormalParameter) and (ancestor::TryStatement))]
</source>Example(s):
<source>
public class Something {
private int q = 15; // field - too short
public static void main( String as[] ) { // formal arg - too short
int r = 20 + q; // local var - too short
for (int i = 0; i < 10; i++) { // not a violation (inside 'for' loop)
r += q;
}
for (Integer i : numbers) { // not a violation (inside 'for-each' loop)
r += q;
}
}
}
</source>
</subsection>
<subsection name="LongVariable">
<p>Since: PMD 0.3</p>
<p>
Fields, formal arguments, or local variable names that are too long can make the code difficult to follow.
</p>
<source>
//VariableDeclaratorId[string-length(@Image) > $minimum]
</source>Example(s):
<source>
public class Something {
int reallyLongIntName = -3; // VIOLATION - Field
public static void main( String argumentsList[] ) { // VIOLATION - Formal
int otherReallyLongName = -5; // VIOLATION - Local
for (int interestingIntIndex = 0; // VIOLATION - For
interestingIntIndex < 10;
interestingIntIndex ++ ) {
}
}
</source>
<p>This rule has the following properties:</p>
<table>
<th>Name</th>
<th>Default Value</th>
<th>Description</th>
<tr>
<td>minimum</td>
<td>17</td>
<td>The variable length reporting threshold</td>
</tr>
</table>
</subsection>
<subsection name="ShortMethodName">
<p>Since: PMD 0.3</p>
<p>
Method names that are very short are not helpful to the reader.
</p>
<source>
//MethodDeclarator[string-length(@Image) < 3]
</source>Example(s):
<source>
public class ShortMethod {
public void a( int i ) { // Violation
}
}
</source>
</subsection>
<subsection name="VariableNamingConventions">
<p>Since: PMD 1.2</p>
<p>
A variable naming conventions rule - customize this to your liking. Currently, it
checks for final variables that should be fully capitalized and non-final variables
that should not include underscores.
</p>
<p>This rule is defined by the following Java class: <a href="../../xref/net/sourceforge/pmd/lang/java/rule/naming/VariableNamingConventionsRule.html">net.sourceforge.pmd.lang.java.rule.naming.VariableNamingConventionsRule</a>
</p>Example(s):
<source>
public class Foo {
public static final int MY_NUM = 0;
public String myTest = "";
DataModule dmTest = new DataModule();
}
</source>
<p>This rule has the following properties:</p>
<table>
<th>Name</th>
<th>Default Value</th>
<th>Description</th>
<tr>
<td>violationSuppressRegex</td>
<td/>
<td>Suppress violations with messages matching a regular expression</td>
</tr>
<tr>
<td>violationSuppressXPath</td>
<td/>
<td>Suppress violations on nodes which match a given relative XPath expression.</td>
</tr>
<tr>
<td>parameterSuffix</td>
<td>[]</td>
<td>Method parameter variable suffixes</td>
</tr>
<tr>
<td>parameterPrefix</td>
<td>[]</td>
<td>Method parameter variable prefixes</td>
</tr>
<tr>
<td>localSuffix</td>
<td>[]</td>
<td>Local variable suffixes</td>
</tr>
<tr>
<td>localPrefix</td>
<td>[]</td>
<td>Local variable prefixes</td>
</tr>
<tr>
<td>memberSuffix</td>
<td>[]</td>
<td>Member variable suffixes</td>
</tr>
<tr>
<td>memberPrefix</td>
<td>[]</td>
<td>Member variable prefixes</td>
</tr>
<tr>
<td>staticSuffix</td>
<td>[]</td>
<td>Static variable suffixes</td>
</tr>
<tr>
<td>staticPrefix</td>
<td>[]</td>
<td>Static variable prefixes</td>
</tr>
<tr>
<td>checkParameters</td>
<td>true</td>
<td>Check constructor and method parameter variables</td>
</tr>
<tr>
<td>checkLocals</td>
<td>true</td>
<td>Check local variables</td>
</tr>
<tr>
<td>checkMembers</td>
<td>true</td>
<td>Check member variables</td>
</tr>
</table>
</subsection>
<subsection name="MethodNamingConventions">
<p>Since: PMD 1.2</p>
<p>
Method names should always begin with a lower case character, and should not contain underscores.
</p>
<p>This rule is defined by the following Java class: <a href="../../xref/net/sourceforge/pmd/lang/java/rule/naming/MethodNamingConventionsRule.html">net.sourceforge.pmd.lang.java.rule.naming.MethodNamingConventionsRule</a>
</p>Example(s):
<source>
public class Foo {
public void fooStuff() {
}
}
</source>
<p>This rule has the following properties:</p>
<table>
<th>Name</th>
<th>Default Value</th>
<th>Description</th>
<tr>
<td>violationSuppressRegex</td>
<td/>
<td>Suppress violations with messages matching a regular expression</td>
</tr>
<tr>
<td>violationSuppressXPath</td>
<td/>
<td>Suppress violations on nodes which match a given relative XPath expression.</td>
</tr>
</table>
</subsection>
<subsection name="ClassNamingConventions">
<p>Since: PMD 1.2</p>
<p>
Class names should always begin with an upper case character.
</p>
<p>This rule is defined by the following Java class: <a href="../../xref/net/sourceforge/pmd/lang/java/rule/naming/ClassNamingConventionsRule.html">net.sourceforge.pmd.lang.java.rule.naming.ClassNamingConventionsRule</a>
</p>Example(s):
<source>
public class Foo {}
</source>
<p>This rule has the following properties:</p>
<table>
<th>Name</th>
<th>Default Value</th>
<th>Description</th>
<tr>
<td>violationSuppressRegex</td>
<td/>
<td>Suppress violations with messages matching a regular expression</td>
</tr>
<tr>
<td>violationSuppressXPath</td>
<td/>
<td>Suppress violations on nodes which match a given relative XPath expression.</td>
</tr>
</table>
</subsection>
<subsection name="AbstractNaming">
<p>Since: PMD 1.4</p>
<p>
Abstract classes should be named 'AbstractXXX'.
</p>
<source>
//ClassOrInterfaceDeclaration
[@Abstract='true' and @Interface='false']
[not (starts-with(@Image,'Abstract'))]
</source>Example(s):
<source>
public abstract class Foo { // should be AbstractFoo
}
</source>
</subsection>
<subsection name="AvoidDollarSigns">
<p>Since: PMD 1.5</p>
<p>
Avoid using dollar signs in variable/method/class/interface names.
</p>
<p>This rule is defined by the following Java class: <a href="../../xref/net/sourceforge/pmd/lang/java/rule/naming/AvoidDollarSignsRule.html">net.sourceforge.pmd.lang.java.rule.naming.AvoidDollarSignsRule</a>
</p>Example(s):
<source>
public class Fo$o { // not a recommended name
}
</source>
<p>This rule has the following properties:</p>
<table>
<th>Name</th>
<th>Default Value</th>
<th>Description</th>
<tr>
<td>violationSuppressRegex</td>
<td/>
<td>Suppress violations with messages matching a regular expression</td>
</tr>
<tr>
<td>violationSuppressXPath</td>
<td/>
<td>Suppress violations on nodes which match a given relative XPath expression.</td>
</tr>
</table>
</subsection>
<subsection name="MethodWithSameNameAsEnclosingClass">
<p>Since: PMD 1.5</p>
<p>
Non-constructor methods should not have the same name as the enclosing class.
</p>
<p>This rule is defined by the following Java class: <a href="../../xref/net/sourceforge/pmd/lang/java/rule/naming/MethodWithSameNameAsEnclosingClassRule.html">net.sourceforge.pmd.lang.java.rule.naming.MethodWithSameNameAsEnclosingClassRule</a>
</p>Example(s):
<source>
public class MyClass {
public MyClass() {} // this is OK because it is a constructor
public void MyClass() {} // this is bad because it is a method
}
</source>
<p>This rule has the following properties:</p>
<table>
<th>Name</th>
<th>Default Value</th>
<th>Description</th>
<tr>
<td>violationSuppressRegex</td>
<td/>
<td>Suppress violations with messages matching a regular expression</td>
</tr>
<tr>
<td>violationSuppressXPath</td>
<td/>
<td>Suppress violations on nodes which match a given relative XPath expression.</td>
</tr>
</table>
</subsection>
<subsection name="SuspiciousHashcodeMethodName">
<p>Since: PMD 1.5</p>
<p>
The method name and return type are suspiciously close to hashCode(), which may denote an intention
to override the hashCode() method.
</p>
<p>This rule is defined by the following Java class: <a href="../../xref/net/sourceforge/pmd/lang/java/rule/naming/SuspiciousHashcodeMethodNameRule.html">net.sourceforge.pmd.lang.java.rule.naming.SuspiciousHashcodeMethodNameRule</a>
</p>Example(s):
<source>
public class Foo {
public int hashcode() { // oops, this probably was supposed to be 'hashCode'
}
}
</source>
<p>This rule has the following properties:</p>
<table>
<th>Name</th>
<th>Default Value</th>
<th>Description</th>
<tr>
<td>violationSuppressRegex</td>
<td/>
<td>Suppress violations with messages matching a regular expression</td>
</tr>
<tr>
<td>violationSuppressXPath</td>
<td/>
<td>Suppress violations on nodes which match a given relative XPath expression.</td>
</tr>
</table>
</subsection>
<subsection name="SuspiciousConstantFieldName">
<p>Since: PMD 2.0</p>
<p>
Field names using all uppercase characters - Sun's Java naming conventions indicating constants - should
be declared as final.
</p>
<source>
//ClassOrInterfaceDeclaration[@Interface='false']
/ClassOrInterfaceBody/ClassOrInterfaceBodyDeclaration/FieldDeclaration
[@Final='false']
[VariableDeclarator/VariableDeclaratorId[upper-case(@Image)=@Image]]
</source>Example(s):
<source>
public class Foo {
// this is bad, since someone could accidentally
// do PI = 2.71828; which is actually e
// final double PI = 3.16; is ok
double PI = 3.16;
}
</source>
</subsection>
<subsection name="SuspiciousEqualsMethodName">
<p>Since: PMD 2.0</p>
<p>
The method name and parameter number are suspiciously close to equals(Object), which can denote an
intention to override the equals(Object) method.
</p>
<source>
//MethodDeclarator[@Image = 'equals']
[
(count(FormalParameters/*) = 1
and not (FormalParameters/FormalParameter/Type/ReferenceType/ClassOrInterfaceType
[@Image = 'Object' or @Image = 'java.lang.Object'])
or not (../ResultType/Type/PrimitiveType[@Image = 'boolean'])
) or (
count(FormalParameters/*) = 2
and ../ResultType/Type/PrimitiveType[@Image = 'boolean']
and FormalParameters//ClassOrInterfaceType[@Image = 'Object' or @Image = 'java.lang.Object']
)
]
| //MethodDeclarator[@Image = 'equal']
[
count(FormalParameters/*) = 1
and FormalParameters/FormalParameter/Type/ReferenceType/ClassOrInterfaceType
[@Image = 'Object' or @Image = 'java.lang.Object']
]
</source>Example(s):
<source>
public class Foo {
public int equals(Object o) {
// oops, this probably was supposed to be boolean equals
}
public boolean equals(String s) {
// oops, this probably was supposed to be equals(Object)
}
public boolean equals(Object o1, Object o2) {
// oops, this probably was supposed to be equals(Object)
}
}
</source>
</subsection>
<subsection name="AvoidFieldNameMatchingTypeName">
<p>Since: PMD 3.0</p>
<p>
It is somewhat confusing to have a field name matching the declaring class name.
This probably means that type and/or field names should be chosen more carefully.
</p>
<p>This rule is defined by the following Java class: <a href="../../xref/net/sourceforge/pmd/lang/java/rule/naming/AvoidFieldNameMatchingTypeNameRule.html">net.sourceforge.pmd.lang.java.rule.naming.AvoidFieldNameMatchingTypeNameRule</a>
</p>Example(s):
<source>
public class Foo extends Bar {
int foo; // There is probably a better name that can be used
}
</source>
<p>This rule has the following properties:</p>
<table>
<th>Name</th>
<th>Default Value</th>
<th>Description</th>
<tr>
<td>violationSuppressRegex</td>
<td/>
<td>Suppress violations with messages matching a regular expression</td>
</tr>
<tr>
<td>violationSuppressXPath</td>
<td/>
<td>Suppress violations on nodes which match a given relative XPath expression.</td>
</tr>
</table>
</subsection>
<subsection name="AvoidFieldNameMatchingMethodName">
<p>Since: PMD 3.0</p>
<p>
It can be confusing to have a field name with the same name as a method. While this is permitted,
having information (field) and actions (method) is not clear naming. Developers versed in
Smalltalk often prefer this approach as the methods denote accessor methods.
</p>
<p>This rule is defined by the following Java class: <a href="../../xref/net/sourceforge/pmd/lang/java/rule/naming/AvoidFieldNameMatchingMethodNameRule.html">net.sourceforge.pmd.lang.java.rule.naming.AvoidFieldNameMatchingMethodNameRule</a>
</p>Example(s):
<source>
public class Foo {
Object bar;
// bar is data or an action or both?
void bar() {
}
}
</source>
<p>This rule has the following properties:</p>
<table>
<th>Name</th>
<th>Default Value</th>
<th>Description</th>
<tr>
<td>violationSuppressRegex</td>
<td/>
<td>Suppress violations with messages matching a regular expression</td>
</tr>
<tr>
<td>violationSuppressXPath</td>
<td/>
<td>Suppress violations on nodes which match a given relative XPath expression.</td>
</tr>
</table>
</subsection>
<subsection name="NoPackage">
<p>Since: PMD 3.3</p>
<p>
Detects when a class or interface does not have a package definition.
</p>
<source>
//ClassOrInterfaceDeclaration[count(preceding::PackageDeclaration) = 0]
</source>Example(s):
<source>
// no package declaration
public class ClassInDefaultPackage {
}
</source>
</subsection>
<subsection name="PackageCase">
<p>Since: PMD 3.3</p>
<p>
Detects when a package definition contains uppercase characters.
</p>
<source>
//PackageDeclaration/Name[lower-case(@Image)!=@Image]
</source>Example(s):
<source>
package com.MyCompany; // should be lowercase name
public class SomeClass {
}
</source>
</subsection>
<subsection name="MisleadingVariableName">
<p>Since: PMD 3.4</p>
<p>
Detects when a non-field has a name starting with 'm_'. This usually denotes a field and could be confusing.
</p>
<source>
//VariableDeclaratorId
[starts-with(@Image, 'm_')]
[not (../../../FieldDeclaration)]
</source>Example(s):
<source>
public class Foo {
private int m_foo; // OK
public void bar(String m_baz) { // Bad
int m_boz = 42; // Bad
}
}
</source>
</subsection>
<subsection name="BooleanGetMethodName">
<p>Since: PMD 4.0</p>
<p>
Methods that return boolean results should be named as predicate statements to denote this.
I.e, 'isReady()', 'hasValues()', 'canCommit()', 'willFail()', etc. Avoid the use of the 'get'
prefix for these methods.
</p>
<source>
//MethodDeclaration[
MethodDeclarator[count(FormalParameters/FormalParameter) = 0 or $checkParameterizedMethods = 'true']
[starts-with(@Image, 'get')]
and
ResultType/Type/PrimitiveType[@Image = 'boolean']
]
</source>Example(s):
<source>
public boolean getFoo(); // bad
public boolean isFoo(); // ok
public boolean getFoo(boolean bar); // ok, unless checkParameterizedMethods=true
</source>
<p>This rule has the following properties:</p>
<table>
<th>Name</th>
<th>Default Value</th>
<th>Description</th>
<tr>
<td>checkParameterizedMethods</td>
<td>false</td>
<td>Check parameterized methods</td>
</tr>
</table>
</subsection>
<subsection name="ShortClassName">
<p>Since: PMD 5.0</p>
<p>
Short Classnames with fewer than e.g. five characters are not recommended.
</p>
<source>
//ClassOrInterfaceDeclaration[string-length(@Image) < $minimum]
</source>Example(s):
<source>
public class Foo {
}
</source>
<p>This rule has the following properties:</p>
<table>
<th>Name</th>
<th>Default Value</th>
<th>Description</th>
<tr>
<td>minimum</td>
<td>5</td>
<td>Number of characters that are required as a minimum for a class name.</td>
</tr>
</table>
</subsection>
<subsection name="GenericsNaming">
<p>Since: PMD 4.2.6</p>
<p>
Names for references to generic values should be limited to a single uppercase letter.
</p>
<source>
//TypeDeclaration/ClassOrInterfaceDeclaration/TypeParameters/TypeParameter[
string-length(@Image) > 1
or
string:upper-case(@Image) != @Image
]
</source>Example(s):
<source>
public interface GenericDao<E extends BaseModel, K extends Serializable> extends BaseDao {
// This is ok...
}
public interface GenericDao<E extends BaseModel, K extends Serializable> {
// Also this
}
public interface GenericDao<e extends BaseModel, K extends Serializable> {
// 'e' should be an 'E'
}
public interface GenericDao<EF extends BaseModel, K extends Serializable> {
// 'EF' is not ok.
}
</source>
</subsection>
</section>
</body>
</document>
| {
"content_hash": "ba160bdeb1759f11aa92071cb42f93e3",
"timestamp": "",
"source": "github",
"line_count": 682,
"max_line_length": 244,
"avg_line_length": 26.428152492668623,
"alnum_prop": 0.6637261429205504,
"repo_name": "byronka/xenos",
"id": "0f4450b17459315dac9512caa99f03c50c2ef7a7",
"size": "18024",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "utils/pmd-bin-5.2.2/src/pmd-java/src/site/xdoc/rules/java/naming.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "102953"
},
{
"name": "C++",
"bytes": "436"
},
{
"name": "CSS",
"bytes": "482910"
},
{
"name": "HTML",
"bytes": "220459885"
},
{
"name": "Java",
"bytes": "31611126"
},
{
"name": "JavaScript",
"bytes": "19708"
},
{
"name": "NSIS",
"bytes": "38770"
},
{
"name": "PLSQL",
"bytes": "19219"
},
{
"name": "Perl",
"bytes": "23704"
},
{
"name": "Python",
"bytes": "3299"
},
{
"name": "SQLPL",
"bytes": "54633"
},
{
"name": "Shell",
"bytes": "192465"
},
{
"name": "XSLT",
"bytes": "499720"
}
],
"symlink_target": ""
} |
namespace caprica { namespace papyrus { namespace expressions {
struct PapyrusNewStructExpression final : public PapyrusExpression
{
PapyrusType type;
explicit PapyrusNewStructExpression(CapricaFileLocation loc, PapyrusType&& tp) : PapyrusExpression(loc), type(std::move(tp)) { }
PapyrusNewStructExpression(const PapyrusNewStructExpression&) = delete;
virtual ~PapyrusNewStructExpression() override = default;
virtual pex::PexValue generateLoad(pex::PexFile*, pex::PexFunctionBuilder& bldr) const override {
namespace op = caprica::pex::op;
bldr << location;
auto dest = bldr.allocTemp(type);
bldr << op::structcreate{ dest };
return dest;
}
virtual void semantic(PapyrusResolutionContext* ctx) override {
type = ctx->resolveType(type);
}
virtual PapyrusType resultType() const override {
return type;
}
};
}}}
| {
"content_hash": "7423e30f5898b0cc9b045a9afbba2bdc",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 130,
"avg_line_length": 30.892857142857142,
"alnum_prop": 0.7364161849710983,
"repo_name": "Orvid/Caprica",
"id": "a3cdfb9bcfc4dcb51e88731be03fd6c66b64b777",
"size": "1052",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Caprica/papyrus/expressions/PapyrusNewStructExpression.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "175"
},
{
"name": "C++",
"bytes": "552913"
},
{
"name": "CMake",
"bytes": "2036"
}
],
"symlink_target": ""
} |
package org.jabref.logic.citationstyle;
import java.util.Objects;
import org.jabref.logic.preview.PreviewLayout;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.database.event.EntriesRemovedEvent;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.event.EntryChangedEvent;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.eventbus.Subscribe;
/**
* Caches the generated Citations for quicker access
* {@link CitationStyleGenerator} generates the citation with JavaScript which may take some time
*/
public class CitationStyleCache {
private static final int CACHE_SIZE = 1024;
private PreviewLayout citationStyle;
private final LoadingCache<BibEntry, String> citationStyleCache;
public CitationStyleCache(BibDatabaseContext databaseContext) {
citationStyleCache = CacheBuilder.newBuilder().maximumSize(CACHE_SIZE).build(new CacheLoader<BibEntry, String>() {
@Override
public String load(BibEntry entry) {
if (citationStyle != null) {
return citationStyle.generatePreview(entry, databaseContext);
} else {
return "";
}
}
});
databaseContext.getDatabase().registerListener(new BibDatabaseEntryListener());
}
/**
* Returns the citation for the given entry.
*/
public String getCitationFor(BibEntry entry) {
return citationStyleCache.getUnchecked(entry);
}
public void setCitationStyle(PreviewLayout citationStyle) {
Objects.requireNonNull(citationStyle);
if (!this.citationStyle.equals(citationStyle)) {
this.citationStyle = citationStyle;
this.citationStyleCache.invalidateAll();
}
}
private class BibDatabaseEntryListener {
/**
* removes the outdated citation of the changed entry
*/
@Subscribe
public void listen(EntryChangedEvent entryChangedEvent) {
citationStyleCache.invalidate(entryChangedEvent.getBibEntry());
}
/**
* removes the citation of the removed entries as they are not needed anymore
*/
@Subscribe
public void listen(EntriesRemovedEvent entriesRemovedEvent) {
for (BibEntry entry : entriesRemovedEvent.getBibEntries()) {
citationStyleCache.invalidate(entry);
}
}
}
}
| {
"content_hash": "e464c9273dc80916234b7fa528935e14",
"timestamp": "",
"source": "github",
"line_count": 75,
"max_line_length": 122,
"avg_line_length": 34.22666666666667,
"alnum_prop": 0.6782236073237242,
"repo_name": "JabRef/jabref",
"id": "f94aaef26d9314500d327b87bf1d0064fd101f96",
"size": "2567",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "src/main/java/org/jabref/logic/citationstyle/CitationStyleCache.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ANTLR",
"bytes": "3775"
},
{
"name": "AppleScript",
"bytes": "1378"
},
{
"name": "Batchfile",
"bytes": "637"
},
{
"name": "CSS",
"bytes": "53157"
},
{
"name": "Groovy",
"bytes": "5094"
},
{
"name": "Java",
"bytes": "8629609"
},
{
"name": "PowerShell",
"bytes": "2024"
},
{
"name": "Python",
"bytes": "9251"
},
{
"name": "Ruby",
"bytes": "20199"
},
{
"name": "Shell",
"bytes": "9437"
},
{
"name": "TeX",
"bytes": "705272"
},
{
"name": "XSLT",
"bytes": "2185"
}
],
"symlink_target": ""
} |
var dns_sd = require('./dns_sd')
, util = require('util')
, MDNSService = require('./mdns_service').MDNSService
;
exports.DNSServiceResolve = function DNSServiceResolve(options) {
options = options || {};
options.flags = options.flags || 0;
options.unwrapTxtRecord =
'unwrapTxtRecord' in options ? options.unwrapTxtRecord : true;
return function DNSServiceResolve(service, next) {
try {
var resolver = new MDNSService();
function on_resolver_done(sdRef, flags, iface, errorCode, fullname,
hosttarget, port, txtRecord, context)
{
try {
var error = dns_sd.buildException(errorCode);
if ( ! error && service.interfaceIndex === iface) {
if (fullname) service.fullname = fullname;
if (hosttarget) service.host = hosttarget;
if (port) service.port = port;
// all services have a TXT record. ignore the empty ones.
if (txtRecord.length > 1) {
service.rawTxtRecord = txtRecord;
if (options.unwrapTxtRecord) {
service.txtRecord = dns_sd.txtRecordBufferToObject(txtRecord)
}
}
}
resolver.stop();
next(error);
} catch (ex) {
resolver.stop();
next(ex);
}
}
dns_sd.DNSServiceResolve(resolver.serviceRef, options.flags,
service.interfaceIndex, service.name, '' + service.type,
service.replyDomain, on_resolver_done, null);
resolver.start();
} catch (ex) {
resolver.stop();
next(ex);
}
};
}
exports.DNSServiceGetAddrInfo = function DNSServiceGetAddrInfo(options) {
options = options || {};
var family_flags = 0;
if ('families' in options) {
if (options.families.indexOf(4) !== -1) {
family_flags |= dns_sd.kDNSServiceProtocol_IPv4;
}
if (options.families.indexOf(6) !== -1) {
family_flags |= dns_sd.kDNSServiceProtocol_IPv6;
}
}
return function DNSServiceGetAddrInfo(service, next) {
try {
var adr_getter = new MDNSService()
, addresses = []
;
function on_get_addr_info_done(sdRef, flags, iface, errorCode, hostname,
address, context)
{
try {
// FIXME: some time throw a error -> 'no such record'
if ( errorCode < 0 ) errorCode = 0;
var error = dns_sd.buildException(errorCode);
if (error) {
adr_getter.stop()
next(error);
} else {
if (iface === service.interfaceIndex) {
addresses.push(address);
}
if ( ! (dns_sd.kDNSServiceFlagsMoreComing & flags)) {
service.addresses = addresses;
adr_getter.stop()
next();
}
}
} catch (ex) {
adr_getter.stop();
next(ex);
}
}
dns_sd.DNSServiceGetAddrInfo(
adr_getter.serviceRef, 0, service.interfaceIndex, family_flags,
service.host, on_get_addr_info_done, null);
adr_getter.start();
} catch (ex) {
adr_getter.stop();
next(ex);
}
}
}
var _getaddrinfo;
try {
var cares = process.binding('cares_wrap');
function getaddrinfo_complete(err, addresses, cb) {
if (addresses) {
cb(undefined, addresses);
} else if (err === 'ENOENT') {
cb(undefined, []);
} else {
cb(errnoException(err, 'getaddrinfo'));
}
}
function getaddrinfo_0_11(host, family, cb) {
var req = new cares.GetAddrInfoReqWrap()
, err = cares.getaddrinfo(req, host, family)
;
req.oncomplete = function oncomplete(err, addresses) {
getaddrinfo_complete(err, addresses, cb);
}
if (err) throw errnoException(err, 'getaddrinfo', host);
}
function getaddrinfo_0_10(host, family, cb) {
var wrap = cares.getaddrinfo(host, family);
if ( ! wrap) {
throw errnoException(process._errno || global.errno, 'getaddrinfo');
}
wrap.oncomplete = function (addresses) {
getaddrinfo_complete((process._errno || global.errno), addresses, cb);
}
}
// node 0.11+ cares.getaddrinfo function uses request object.
// use appropriate version based on node version number
if (Number(process.version.match(/^v(\d+\.\d+)/)[1]) > 0.1) {
_getaddrinfo = getaddrinfo_0_11;
} else {
_getaddrinfo = getaddrinfo_0_10;
}
} catch (ex) {
_getaddrinfo = process.binding('net').getaddrinfo;
}
exports.getaddrinfo = function getaddrinfo(options) {
options = options || {};
var families = options.families || [4, 6];
return function getaddrinfo(service, next) {
var last_error
, counter = 0
;
// XXX in older versions of node a zero family value is not supported
families.forEach(function(family) {
_getaddrinfo(service.host, family, function(error, addresses) {
if (error) {
last_error = error
} else {
service.addresses = (service.addresses || []).concat(addresses);
}
if (++counter === families.length) {
next(last_error);
}
});
});
}
}
function unique(array) {
var o = {} , p , r = [] ;
array.forEach(function(e) { o[e] = undefined });
for (p in o) { r.push(p) }
return r;
}
exports.makeAddressesUnique = function makeAddressesUnique() {
return function makeAddressesUnique(service, next) {
service.addresses = unique(service.addresses);
next();
}
}
exports.filterAddresses = function filterAddresses(filter_function) {
return function filterAddresses(service, next) {
service.addresses = (service.addresses || []).filter(filter_function);
next();
}
}
exports.logService = function logService() {
return function logService(service, next) {
console.log(service);
next();
}
}
function errnoException(errorno, syscall) {
// TODO make this more compatible with ErrnoException from src/node.cc
// Once all of Node is using this function the ErrnoException from
// src/node.cc should be removed.
var e = new Error(syscall + ' ' + errorno);
// For backwards compatibility. libuv returns ENOENT on NXDOMAIN.
if (errorno == 'ENOENT') {
errorno = 'ENOTFOUND'
}
e.errno = e.code = errorno;
e.syscall = syscall;
return e;
}
| {
"content_hash": "7d502b42dede92b2e14f7e74bf8adb27",
"timestamp": "",
"source": "github",
"line_count": 214,
"max_line_length": 78,
"avg_line_length": 29.55140186915888,
"alnum_prop": 0.5951929158760279,
"repo_name": "tajddin/voiceplay",
"id": "e54dfa556a29dfe5625e190e9bb5caff4b9abdc6",
"size": "6324",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "node_modules/airplay2/node_modules/mdns/lib/resolver_sequence_tasks.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "29913"
}
],
"symlink_target": ""
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.9.1"/>
<title>LO21 | Pistache: Member List</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { init_search(); });
</script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectlogo"><img alt="Logo" src="logomini.png"/></td>
<td style="padding-left: 0.5em;">
<div id="projectname">LO21 | Pistache
</div>
<div id="projectbrief">Projet de LO21 de Loïc Deryckère et Mewen Michel</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.9.1 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="namespaces.html"><span>Namespaces</span></a></li>
<li class="current"><a href="annotated.html"><span>Classes</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="annotated.html"><span>Class List</span></a></li>
<li><a href="classes.html"><span>Class Index</span></a></li>
<li><a href="inherits.html"><span>Class Hierarchy</span></a></li>
<li><a href="functions.html"><span>Class Members</span></a></li>
</ul>
</div>
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
</div><!-- top -->
<div class="header">
<div class="headertitle">
<div class="title">Composite Member List</div> </div>
</div><!--header-->
<div class="contents">
<p>This is the complete list of members for <a class="el" href="class_composite.html">Composite</a>, including all inherited members.</p>
<table class="directory">
<tr class="even"><td class="entry"><a class="el" href="class_composite.html#ad8dce9e36cfb7386331babc980c382ff">addCompo</a>(Tache *t)</td><td class="entry"><a class="el" href="class_composite.html">Composite</a></td><td class="entry"></td></tr>
<tr><td class="entry"><a class="el" href="class_composite.html#ab0d63970716648141fbc24e7d77815a2">addItem</a>(Tache *t)</td><td class="entry"><a class="el" href="class_composite.html">Composite</a></td><td class="entry"><span class="mlabel">virtual</span></td></tr>
<tr class="even"><td class="entry"><a class="el" href="class_composite.html#a36da340a18bdf872a180c9657c5996c2">afficher</a>(ostream &f)</td><td class="entry"><a class="el" href="class_composite.html">Composite</a></td><td class="entry"><span class="mlabel">virtual</span></td></tr>
<tr><td class="entry"><a class="el" href="class_composite.html#a99b8848e80b13dbf3ce3c48846cdf20a">CompoIterator</a> class</td><td class="entry"><a class="el" href="class_composite.html">Composite</a></td><td class="entry"><span class="mlabel">friend</span></td></tr>
<tr class="even"><td class="entry"><a class="el" href="class_composite.html#af4ed8de948b2e2ffbd5a190aa1bc5260">getCompo</a>(const string &id)</td><td class="entry"><a class="el" href="class_composite.html">Composite</a></td><td class="entry"></td></tr>
<tr><td class="entry"><a class="el" href="class_composite.html#a490a29347d32a8916f6a636e6de6d1ed">getCompo</a>(const string &code) const </td><td class="entry"><a class="el" href="class_composite.html">Composite</a></td><td class="entry"></td></tr>
<tr class="even"><td class="entry"><a class="el" href="class_composite.html#a21cf28bf7b0aa43af3804145c7e0b25f">getCompoIterator</a>()</td><td class="entry"><a class="el" href="class_composite.html">Composite</a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr><td class="entry"><a class="el" href="class_tache.html#a8cba5e74f4ee6b31e29d0339dbe470fe">getDateDisponibilite</a>() const </td><td class="entry"><a class="el" href="class_tache.html">Tache</a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr class="even"><td class="entry"><a class="el" href="class_tache.html#abe0dbe94fc6908ba5e3cb7fd2fa90f92">getDateEcheance</a>() const </td><td class="entry"><a class="el" href="class_tache.html">Tache</a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr><td class="entry"><a class="el" href="class_tache.html#a1fe8754733f0b85c232d91851cf61891">getId</a>() const </td><td class="entry"><a class="el" href="class_tache.html">Tache</a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr class="even"><td class="entry"><a class="el" href="class_tache.html#a709d4d7d5c25604b6e9a5c37b74fa4a6">getIterator</a>()</td><td class="entry"><a class="el" href="class_tache.html">Tache</a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr><td class="entry"><a class="el" href="class_composite.html#a8f2329eb1c8e193a820243948b9a9cf7">getNbCompo</a>()</td><td class="entry"><a class="el" href="class_composite.html">Composite</a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr class="even"><td class="entry"><a class="el" href="class_tache.html#ac597ce580ad0b32c373b329d4da839ad">getNbPred</a>()</td><td class="entry"><a class="el" href="class_tache.html">Tache</a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr><td class="entry"><a class="el" href="class_tache.html#ab29bfb6c79337fbc9dc5618195f12f8d">getPrecedence</a>(const string &id)</td><td class="entry"><a class="el" href="class_tache.html">Tache</a></td><td class="entry"></td></tr>
<tr class="even"><td class="entry"><a class="el" href="class_tache.html#af995526e12eed76ffa2a4ba7b6fb7a90">getPrecedence</a>(const string &code) const </td><td class="entry"><a class="el" href="class_tache.html">Tache</a></td><td class="entry"></td></tr>
<tr><td class="entry"><a class="el" href="class_tache.html#aa6d1abc3712b5a8b571bb3c131129ac7">getProjet</a>() const </td><td class="entry"><a class="el" href="class_tache.html">Tache</a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr class="even"><td class="entry"><a class="el" href="class_tache.html#a18bda9873a4643a7bebe4905110e3814">getProjet</a>()</td><td class="entry"><a class="el" href="class_tache.html">Tache</a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr><td class="entry"><a class="el" href="class_composite.html#a6def8410e8a78678b488d1610266ee5b">getStatut</a>()</td><td class="entry"><a class="el" href="class_composite.html">Composite</a></td><td class="entry"><span class="mlabel">virtual</span></td></tr>
<tr class="even"><td class="entry"><a class="el" href="class_tache.html#ab6af5354e29498ab43ab3cc826b0aac4">getTitre</a>() const </td><td class="entry"><a class="el" href="class_tache.html">Tache</a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr><td class="entry"><a class="el" href="class_composite.html#a4dd23b6bafdc87f05f0cb7d19e459f94">isFinished</a>(const Date &d, const Horaire &h)</td><td class="entry"><a class="el" href="class_composite.html">Composite</a></td><td class="entry"><span class="mlabel">virtual</span></td></tr>
<tr class="even"><td class="entry"><a class="el" href="class_tache.html#a72df18190512de6ca437492a3664d05a">isPrecedence</a>() const </td><td class="entry"><a class="el" href="class_tache.html">Tache</a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr><td class="entry"><a class="el" href="class_composite.html#a38fbb5005db8a763fec1c8c04f63e1e0">isPrecedencePotentielle</a>(const string &id)</td><td class="entry"><a class="el" href="class_composite.html">Composite</a></td><td class="entry"><span class="mlabel">virtual</span></td></tr>
<tr class="even"><td class="entry"><a class="el" href="class_composite.html#a8bbbf008527c73203db26f0f44c5e9d8">Projet::ajouterComposite</a>(const string &t, const Date &dispo, const Date &deadline)</td><td class="entry"><a class="el" href="class_composite.html">Composite</a></td><td class="entry"><span class="mlabel">friend</span></td></tr>
<tr><td class="entry"><a class="el" href="class_tache.html#a56de6bd26a4a5028c01481ccdededd54">setDatesDisponibiliteEcheance</a>(const Date &disp, const Date &e)</td><td class="entry"><a class="el" href="class_tache.html">Tache</a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr class="even"><td class="entry"><a class="el" href="class_tache.html#a4ea66e1007e692875199d4027e724a85">setId</a>(const string &id)</td><td class="entry"><a class="el" href="class_tache.html">Tache</a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr><td class="entry"><a class="el" href="class_tache.html#a191acd8b10c22b8e7a533aa8f237b907">setTitre</a>(const string &t)</td><td class="entry"><a class="el" href="class_tache.html">Tache</a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr class="even"><td class="entry"><a class="el" href="class_tache.html#a026b068c4e49643d6fec30c9b915ddca">Tache</a>(const string &id, const string &t, const Date &dispo, const Date &deadline, Projet *p)</td><td class="entry"><a class="el" href="class_tache.html">Tache</a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr><td class="entry"><a class="el" href="class_composite.html#ab57477d717423de47a26eb6981ab5914">update</a>(string id, string t, Date d, Date e)</td><td class="entry"><a class="el" href="class_composite.html">Composite</a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr class="even"><td class="entry"><a class="el" href="class_composite.html#a872bf1fe01072258e23d5e9c25f8b57a">update</a>(string t, Date d, Date e)</td><td class="entry"><a class="el" href="class_composite.html">Composite</a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr><td class="entry"><a class="el" href="class_tache.html#acefc2a88516ef4d8bd7b25afcf769e9c">~Tache</a>()</td><td class="entry"><a class="el" href="class_tache.html">Tache</a></td><td class="entry"><span class="mlabel">inline</span><span class="mlabel">virtual</span></td></tr>
</table></div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated on Sun Jun 14 2015 20:59:15 for LO21 | Pistache by  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.9.1
</small></address>
</body>
</html>
| {
"content_hash": "8b8c6a4849ae79277212de33c2d75bfa",
"timestamp": "",
"source": "github",
"line_count": 133,
"max_line_length": 358,
"avg_line_length": 94.16541353383458,
"alnum_prop": 0.6833280102203769,
"repo_name": "mmewen/LO21",
"id": "5de11463a02d09e0fc96e3868d9be8621192235b",
"size": "12526",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "doc/html/class_composite-members.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "131252"
},
{
"name": "HTML",
"bytes": "4571"
},
{
"name": "QMake",
"bytes": "342"
}
],
"symlink_target": ""
} |
class AddIndexToTitles < ActiveRecord::Migration
def change
add_index :titles, :title
end
end
| {
"content_hash": "bbc0778706ae79c6bda28fa6afcff21f",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 48,
"avg_line_length": 20.4,
"alnum_prop": 0.7450980392156863,
"repo_name": "MiraitSystems/enju_trunk",
"id": "9d21862fefd9e460bc5d120eb9118429a8e8f9f7",
"size": "102",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "db/migrate/20140801061958_add_index_to_titles.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "7110"
},
{
"name": "CSS",
"bytes": "127876"
},
{
"name": "CoffeeScript",
"bytes": "1832"
},
{
"name": "HTML",
"bytes": "1391134"
},
{
"name": "JavaScript",
"bytes": "185899"
},
{
"name": "Perl",
"bytes": "15436"
},
{
"name": "Perl6",
"bytes": "637"
},
{
"name": "Ruby",
"bytes": "3866788"
},
{
"name": "Shell",
"bytes": "9055"
}
],
"symlink_target": ""
} |
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "6b8cbaf04d4f05141b24dadc04b24f45",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.23076923076923,
"alnum_prop": 0.6917293233082706,
"repo_name": "mdoering/backbone",
"id": "95d5a9c9ceeebe9fef291f8a2716e381eb748734",
"size": "184",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Ericales/Lecythidaceae/Eschweilera/Eschweilera pedicellata/ Syn. Lecythis macrophylla/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
/**
* @file Represents a websocket server
*/
'use strict'
function nop() {}
var util = require('util'),
net = require('net'),
tls = require('tls'),
events = require('events'),
Connection
/**
* @callback SelectProtocolCallback
* @param {Connection} connection
* @param {Array<string>} protocols
* @returns {?string}
*/
/**
* Creates a new ws server and starts listening for new connections
* @class
* @param {boolean} secure indicates if it should use tls
* @param {Object} [options] will be passed to net.createServer() or tls.createServer()
* @param {Array<string>} [options.validProtocols]
* @param {SelectProtocolCallback} [options.selectProtocol]
* @param {Function} [callback] will be added as "connection" listener
* @inherits EventEmitter
* @event listening
* @event close
* @event error an error object is passed
* @event connection a Connection object is passed
*/
function Server(secure, options, callback) {
var that = this
if (typeof options === 'function') {
callback = options
options = undefined
}
var onConnection = function (socket) {
var conn = new Connection(socket, that, function () {
that.connections.push(conn)
conn.removeListener('error', nop)
that.emit('connection', conn)
})
conn.on('close', function () {
var pos = that.connections.indexOf(conn)
if (pos !== -1) {
that.connections.splice(pos, 1)
}
})
// Ignore errors before the connection is established
conn.on('error', nop)
}
if (secure) {
this.socket = tls.createServer(options, onConnection)
} else {
this.socket = net.createServer(options, onConnection)
}
this.socket.on('close', function () {
that.emit('close')
})
this.socket.on('error', function (err) {
that.emit('error', err)
})
this.connections = []
// super constructor
events.EventEmitter.call(this)
if (callback) {
this.on('connection', callback)
}
// Add protocol agreement handling
/**
* @member {?SelectProtocolCallback}
* @private
*/
this._selectProtocol = null
if (options && options.selectProtocol) {
// User-provided logic
this._selectProtocol = options.selectProtocol
} else if (options && options.validProtocols) {
// Default logic
this._selectProtocol = this._buildSelectProtocol(options.validProtocols)
}
}
util.inherits(Server, events.EventEmitter)
module.exports = Server
Connection = require('./Connection')
/**
* Start listening for connections
* @param {number} port
* @param {string} [host]
* @param {Function} [callback] will be added as "connection" listener
*/
Server.prototype.listen = function (port, host, callback) {
var that = this
if (typeof host === 'function') {
callback = host
host = undefined
}
if (callback) {
this.on('listening', callback)
}
this.socket.listen(port, host, function () {
that.emit('listening')
})
return this
}
/**
* Stops the server from accepting new connections and keeps existing connections.
* This function is asynchronous, the server is finally closed when all connections are ended and the server emits a 'close' event.
* The optional callback will be called once the 'close' event occurs.
* @param {function()} [callback]
*/
Server.prototype.close = function (callback) {
if (callback) {
this.once('close', callback)
}
this.socket.close()
}
/**
* Create a resolver to pick the client's most preferred protocol the server recognises
* @param {Array<string>} validProtocols
* @returns {SelectProtocolCallback}
* @private
*/
Server.prototype._buildSelectProtocol = function (validProtocols) {
return function (conn, protocols) {
var i
for (i = 0; i < protocols.length; i++) {
if (validProtocols.indexOf(protocols[i]) !== -1) {
// A valid protocol was found
return protocols[i]
}
}
// No agreement
}
} | {
"content_hash": "52297f429ca1667b33e18db3cb1f1cf7",
"timestamp": "",
"source": "github",
"line_count": 158,
"max_line_length": 131,
"avg_line_length": 24.974683544303797,
"alnum_prop": 0.6606690319310694,
"repo_name": "eltitopera/TFM",
"id": "04f572e7762c281ae70caf868b2ffbc973c4dd28",
"size": "3946",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "displayTweets/testNode/node_modules/nodejs-websocket/Server.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "1508"
},
{
"name": "Java",
"bytes": "478407"
},
{
"name": "JavaScript",
"bytes": "1313"
},
{
"name": "Python",
"bytes": "7085"
},
{
"name": "Shell",
"bytes": "3104"
}
],
"symlink_target": ""
} |
/*
* To change this template, choose Users | Templates
* and open the template in the editor.
*/
Ext.define('sisprod.view.SystemUserGroup.UpdateSystemUserGroup', {
extend: 'sisprod.view.base.BaseDataWindow',
alias: 'widget.updateSystemUserGroup',
require: [
'sisprod.view.base.BaseDataWindow'
],
messages:{
systemUserGroupNameLabel:'Name'
},
autoMappingOptions: {
autoMapping: false
},
title: 'Update System User Group',
modal: true,
width: 400,
initComponent:function(){
var me=this;
me.formOptions= {
bodyPadding: 2,
items: [
{
xtype: 'hiddenfield',
name: 'id'
},
{
xtype: 'textfield',
grow: true,
name: 'groupName',
fieldLabel:me.messages.systemUserGroupNameLabel,
fieldStyle: {
textTransform: 'uppercase'
},
anchor: '100%',
allowBlank: false,
maxLength: 100
}
]
};
me.callParent(arguments);
}
}); | {
"content_hash": "d9f4617ebc362b02bcb42385727b9750",
"timestamp": "",
"source": "github",
"line_count": 46,
"max_line_length": 66,
"avg_line_length": 26.652173913043477,
"alnum_prop": 0.4820554649265905,
"repo_name": "jgin/testphp",
"id": "54431cf83bae1a2b466e09dbaef1fc7ee0fc9cfb",
"size": "1226",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "web/bundles/hrmpayroll/app/view/SystemUserGroup/UpdateSystemUserGroup.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "743341"
},
{
"name": "JavaScript",
"bytes": "26577383"
},
{
"name": "PHP",
"bytes": "87904"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.