| cdens |
Component Density for Parameterized MVN Mixture Models |
| cdensE |
Component Density for a Parameterized MVN Mixture Model |
| cdensEEE |
Component Density for a Parameterized MVN Mixture Model |
| cdensEEI |
Component Density for a Parameterized MVN Mixture Model |
| cdensEEV |
Component Density for a Parameterized MVN Mixture Model |
| cdensEII |
Component Density for a Parameterized MVN Mixture Model |
| cdensEVE |
Component Density for a Parameterized MVN Mixture Model |
| cdensEVI |
Component Density for a Parameterized MVN Mixture Model |
| cdensEVV |
Component Density for a Parameterized MVN Mixture Model |
| cdensV |
Component Density for a Parameterized MVN Mixture Model |
| cdensVEE |
Component Density for a Parameterized MVN Mixture Model |
| cdensVEI |
Component Density for a Parameterized MVN Mixture Model |
| cdensVEV |
Component Density for a Parameterized MVN Mixture Model |
| cdensVII |
Component Density for a Parameterized MVN Mixture Model |
| cdensVVE |
Component Density for a Parameterized MVN Mixture Model |
| cdensVVI |
Component Density for a Parameterized MVN Mixture Model |
| cdensVVV |
Component Density for a Parameterized MVN Mixture Model |
| cdensX |
Component Density for a Parameterized MVN Mixture Model |
| cdensXII |
Component Density for a Parameterized MVN Mixture Model |
| cdensXXI |
Component Density for a Parameterized MVN Mixture Model |
| cdensXXX |
Component Density for a Parameterized MVN Mixture Model |
| cdfMclust |
Cumulative Distribution and Quantiles for a univariate Gaussian mixture distribution |
| chevron |
Simulated minefield data |
| classError |
Classification error |
| classPriorProbs |
Estimation of class prior probabilities by EM algorithm |
| clPairs |
Pairwise Scatter Plots showing Classification |
| clPairsLegend |
Pairwise Scatter Plots showing Classification |
| clustCombi |
Combining Gaussian Mixture Components for Clustering |
| clustCombiOptim |
Optimal number of clusters obtained by combining mixture components |
| combiPlot |
Plot Classifications Corresponding to Successive Combined Solutions |
| combiTree |
Tree structure obtained from combining mixture components |
| combMat |
Combining Matrix |
| coordProj |
Coordinate projections of multidimensional data modeled by an MVN mixture. |
| covw |
Weighted means, covariance and scattering matrices conditioning on a weighted matrix |
| crimcoords |
Discriminant coordinates data projection |
| cross |
Simulated Cross Data |
| cv.MclustDA |
Deprecated Functions in mclust package |
| cv1EMtrain |
Deprecated Functions in mclust package |
| cvMclustDA |
MclustDA cross-validation |
| em |
EM algorithm starting with E-step for parameterized Gaussian mixture models |
| EMclust |
BIC for Model-Based Clustering |
| emControl |
Set control values for use with the EM algorithm |
| emE |
EM algorithm starting with E-step for a parameterized Gaussian mixture model |
| emEEE |
EM algorithm starting with E-step for a parameterized Gaussian mixture model |
| emEEI |
EM algorithm starting with E-step for a parameterized Gaussian mixture model |
| emEEV |
EM algorithm starting with E-step for a parameterized Gaussian mixture model |
| emEII |
EM algorithm starting with E-step for a parameterized Gaussian mixture model |
| emEVE |
EM algorithm starting with E-step for a parameterized Gaussian mixture model |
| emEVI |
EM algorithm starting with E-step for a parameterized Gaussian mixture model |
| emEVV |
EM algorithm starting with E-step for a parameterized Gaussian mixture model |
| emV |
EM algorithm starting with E-step for a parameterized Gaussian mixture model |
| emVEE |
EM algorithm starting with E-step for a parameterized Gaussian mixture model |
| emVEI |
EM algorithm starting with E-step for a parameterized Gaussian mixture model |
| emVEV |
EM algorithm starting with E-step for a parameterized Gaussian mixture model |
| emVII |
EM algorithm starting with E-step for a parameterized Gaussian mixture model |
| emVVE |
EM algorithm starting with E-step for a parameterized Gaussian mixture model |
| emVVI |
EM algorithm starting with E-step for a parameterized Gaussian mixture model |
| emVVV |
EM algorithm starting with E-step for a parameterized Gaussian mixture model |
| emX |
EM algorithm starting with E-step for a parameterized Gaussian mixture model |
| emXII |
EM algorithm starting with E-step for a parameterized Gaussian mixture model |
| emXXI |
EM algorithm starting with E-step for a parameterized Gaussian mixture model |
| emXXX |
EM algorithm starting with E-step for a parameterized Gaussian mixture model |
| entPlot |
Plot Entropy Plots |
| errorBars |
Draw error bars on a plot |
| estep |
E-step for parameterized Gaussian mixture models. |
| estepE |
E-step in the EM algorithm for a parameterized Gaussian mixture model. |
| estepEEE |
E-step in the EM algorithm for a parameterized Gaussian mixture model. |
| estepEEI |
E-step in the EM algorithm for a parameterized Gaussian mixture model. |
| estepEEV |
E-step in the EM algorithm for a parameterized Gaussian mixture model. |
| estepEII |
E-step in the EM algorithm for a parameterized Gaussian mixture model. |
| estepEVE |
E-step in the EM algorithm for a parameterized Gaussian mixture model. |
| estepEVI |
E-step in the EM algorithm for a parameterized Gaussian mixture model. |
| estepEVV |
E-step in the EM algorithm for a parameterized Gaussian mixture model. |
| estepV |
E-step in the EM algorithm for a parameterized Gaussian mixture model. |
| estepVEE |
E-step in the EM algorithm for a parameterized Gaussian mixture model. |
| estepVEI |
E-step in the EM algorithm for a parameterized Gaussian mixture model. |
| estepVEV |
E-step in the EM algorithm for a parameterized Gaussian mixture model. |
| estepVII |
E-step in the EM algorithm for a parameterized Gaussian mixture model. |
| estepVVE |
E-step in the EM algorithm for a parameterized Gaussian mixture model. |
| estepVVI |
E-step in the EM algorithm for a parameterized Gaussian mixture model. |
| estepVVV |
E-step in the EM algorithm for a parameterized Gaussian mixture model. |
| EuroUnemployment |
Unemployment data for European countries in 2014 |
| ex4.1 |
Simulated Example Datasets From Baudry et al. (2010) |
| ex4.2 |
Simulated Example Datasets From Baudry et al. (2010) |
| ex4.3 |
Simulated Example Datasets From Baudry et al. (2010) |
| ex4.4.1 |
Simulated Example Datasets From Baudry et al. (2010) |
| ex4.4.2 |
Simulated Example Datasets From Baudry et al. (2010) |
| majorityVote |
Majority vote |
| map |
Classification given Probabilities |
| mapClass |
Correspondence between classifications |
| matchCluster |
Missing data imputation via the 'mix' package |
| Mclust |
Model-Based Clustering |
| mclust |
Gaussian Mixture Modelling for Model-Based Clustering, Classification, and Density Estimation |
| mclust.options |
Default values for use with MCLUST package |
| mclust1Dplot |
Plot one-dimensional data modeled by an MVN mixture. |
| mclust2Dplot |
Plot two-dimensional data modelled by an MVN mixture |
| mclustBIC |
BIC for Model-Based Clustering |
| mclustBICupdate |
Update BIC values for parameterized Gaussian mixture models |
| MclustBootstrap |
Resampling-based Inference for Gaussian finite mixture models |
| mclustBootstrapLRT |
Bootstrap Likelihood Ratio Test for the Number of Mixture Components |
| MclustDA |
MclustDA discriminant analysis |
| MclustDR |
Dimension reduction for model-based clustering and classification |
| MclustDRrecoverdir |
Subset selection for GMMDR directions based on BIC |
| MclustDRsubsel |
Subset selection for GMMDR directions based on BIC |
| MclustDRsubsel1cycle |
Subset selection for GMMDR directions based on BIC |
| MclustDRsubsel_classif |
Subset selection for GMMDR directions based on BIC |
| MclustDRsubsel_cluster |
Subset selection for GMMDR directions based on BIC |
| mclustICL |
ICL Criterion for Model-Based Clustering |
| mclustLoglik |
Log-likelihood from a table of BIC values for parameterized Gaussian mixture models |
| mclustModel |
Best model based on BIC |
| mclustModelNames |
MCLUST Model Names |
| MclustSSC |
MclustSSC semi-supervised classification |
| mclustVariance |
Template for variance specification for parameterized Gaussian mixture models |
| me |
EM algorithm starting with M-step for parameterized MVN mixture models |
| me.weighted |
EM algorithm with weights starting with M-step for parameterized MVN mixture models |
| meE |
EM algorithm starting with M-step for a parameterized Gaussian mixture model |
| meEEE |
EM algorithm starting with M-step for a parameterized Gaussian mixture model |
| meEEI |
EM algorithm starting with M-step for a parameterized Gaussian mixture model |
| meEEV |
EM algorithm starting with M-step for a parameterized Gaussian mixture model |
| meEII |
EM algorithm starting with M-step for a parameterized Gaussian mixture model |
| meEVE |
EM algorithm starting with M-step for a parameterized Gaussian mixture model |
| meEVI |
EM algorithm starting with M-step for a parameterized Gaussian mixture model |
| meEVV |
EM algorithm starting with M-step for a parameterized Gaussian mixture model |
| meV |
EM algorithm starting with M-step for a parameterized Gaussian mixture model |
| meVEE |
EM algorithm starting with M-step for a parameterized Gaussian mixture model |
| meVEI |
EM algorithm starting with M-step for a parameterized Gaussian mixture model |
| meVEV |
EM algorithm starting with M-step for a parameterized Gaussian mixture model |
| meVII |
EM algorithm starting with M-step for a parameterized Gaussian mixture model |
| meVVE |
EM algorithm starting with M-step for a parameterized Gaussian mixture model |
| meVVI |
EM algorithm starting with M-step for a parameterized Gaussian mixture model |
| meVVV |
EM algorithm starting with M-step for a parameterized Gaussian mixture model |
| meX |
EM algorithm starting with M-step for a parameterized Gaussian mixture model |
| meXII |
EM algorithm starting with M-step for a parameterized Gaussian mixture model |
| meXXI |
EM algorithm starting with M-step for a parameterized Gaussian mixture model |
| meXXX |
EM algorithm starting with M-step for a parameterized Gaussian mixture model |
| mstep |
M-step for parameterized Gaussian mixture models |
| mstepE |
M-step for a parameterized Gaussian mixture model |
| mstepEEE |
M-step for a parameterized Gaussian mixture model |
| mstepEEI |
M-step for a parameterized Gaussian mixture model |
| mstepEEV |
M-step for a parameterized Gaussian mixture model |
| mstepEII |
M-step for a parameterized Gaussian mixture model |
| mstepEVE |
M-step for a parameterized Gaussian mixture model |
| mstepEVI |
M-step for a parameterized Gaussian mixture model |
| mstepEVV |
M-step for a parameterized Gaussian mixture model |
| mstepV |
M-step for a parameterized Gaussian mixture model |
| mstepVEE |
M-step for a parameterized Gaussian mixture model |
| mstepVEI |
M-step for a parameterized Gaussian mixture model |
| mstepVEV |
M-step for a parameterized Gaussian mixture model |
| mstepVII |
M-step for a parameterized Gaussian mixture model |
| mstepVVE |
M-step for a parameterized Gaussian mixture model |
| mstepVVI |
M-step for a parameterized Gaussian mixture model |
| mstepVVV |
M-step for a parameterized Gaussian mixture model |
| mvn |
Univariate or Multivariate Normal Fit |
| mvnX |
Univariate or Multivariate Normal Fit |
| mvnXII |
Univariate or Multivariate Normal Fit |
| mvnXXI |
Univariate or Multivariate Normal Fit |
| mvnXXX |
Univariate or Multivariate Normal Fit |
| sigma2decomp |
Convert mixture component covariances to decomposition form. |
| sim |
Simulate from Parameterized MVN Mixture Models |
| simE |
Simulate from a Parameterized MVN Mixture Model |
| simEEE |
Simulate from a Parameterized MVN Mixture Model |
| simEEI |
Simulate from a Parameterized MVN Mixture Model |
| simEEV |
Simulate from a Parameterized MVN Mixture Model |
| simEII |
Simulate from a Parameterized MVN Mixture Model |
| simEVE |
Simulate from a Parameterized MVN Mixture Model |
| simEVI |
Simulate from a Parameterized MVN Mixture Model |
| simEVV |
Simulate from a Parameterized MVN Mixture Model |
| simV |
Simulate from a Parameterized MVN Mixture Model |
| simVEE |
Simulate from a Parameterized MVN Mixture Model |
| simVEI |
Simulate from a Parameterized MVN Mixture Model |
| simVEV |
Simulate from a Parameterized MVN Mixture Model |
| simVII |
Simulate from a Parameterized MVN Mixture Model |
| simVVE |
Simulate from a Parameterized MVN Mixture Model |
| simVVI |
Simulate from a Parameterized MVN Mixture Model |
| simVVV |
Simulate from a Parameterized MVN Mixture Model |
| summary.clustCombi |
Combining Gaussian Mixture Components for Clustering |
| summary.gmmhd |
Identifying Connected Components in Gaussian Finite Mixture Models for Clustering |
| summary.Mclust |
Summarizing Gaussian Finite Mixture Model Fits |
| summary.mclustBIC |
Summary function for model-based clustering via BIC |
| summary.MclustBootstrap |
Summary Function for Bootstrap Inference for Gaussian Finite Mixture Models |
| summary.MclustDA |
Summarizing discriminant analysis based on Gaussian finite mixture modeling |
| summary.MclustDR |
Summarizing dimension reduction method for model-based clustering and classification |
| summary.MclustDRsubsel |
Subset selection for GMMDR directions based on BIC |
| summary.mclustICL |
ICL Criterion for Model-Based Clustering |
| summary.MclustSSC |
Summarizing semi-supervised classification model based on Gaussian finite mixtures |
| summaryMclustBIC |
Summary function for model-based clustering via BIC |
| summaryMclustBICn |
Summary function for model-based clustering via BIC |
| surfacePlot |
Density or uncertainty surface for bivariate mixtures |


| Vendor Name : | LEXI-TECH INTERNATIONAL |
|---|---|
| Reference Number : | 8131-06-0006 |
| Contract Date : | 2006-07-17 |
| Description of Work : | 494 Translation Services |
| Description (more details) : | N/A |
| Contract Period : | 2006-07-06 to 2007-03-31 |
| Delivery Date : | N/A |
| Current Contract Value : | $10,600.00 |
| Comments : | N/A |


usort
(PHP 4, PHP 5, PHP 7)
usort — 使用用户自定义的比较函数对数组中的值进行排序
说明
bool usort ( array &$array , callable $cmp_function )
本函数将用用户自定义的比较函数对一个数组中的值进行排序。如果要排序的数组需要用
一种不寻常的标准进行排序，那么应该使用此函数。
Note:
如果两个成员比较结果相同，则它们在排序后的数组中的顺序未经定义。
Note: 此函数为 array 中的元素赋与新的键名。这将删除原有的键名，而不是仅仅将
键名重新排序。
参数
array
输入的数组
cmp_function
在第一个参数小于，等于或大于第二个参数时，该比较函数必须相应地返回一个小于
，等于或大于 0 的整数。
int callback ( mixed $a, mixed $b )
Caution
Returning non-integer values from the comparison function, such as float,
will result in an internal cast to integer of the callback's return value.
So values such as 0.99 and 0.1 will both be cast to an integer value of 0,
which will compare such values as equal.
返回值
成功时返回 TRUE，或者在失败时返回 FALSE。
更新日志
版本 说明
4.1.0 引进了新的排序算法。用户自定义函数 cmp_function 将不再保留这些单元的原有
顺序。
范例
Example #1 usort() 例子
$value) {
echo "$key: $value\n";
}
?>
以上例程会输出：
0: 1
1: 2
2: 3
3: 5
4: 6
Note:
很明显在这个小例子中用 sort() 函数更合适。
Example #2 使用多维数组的 usort() 例子
当排序多维数组时，$a 和 $b 包含到数组第一个索引的引用。
以上例程会输出：
$fruits[0]: apples
$fruits[1]: grapes
$fruits[2]: lemons
Example #3 usort() example using a member function of an object
name = $name;
}
/* This is the static comparing function: */
static function cmp_obj($a, $b)
{
$al = strtolower($a->name);
$bl = strtolower($b->name);
if ($al == $bl) {
return 0;
}
return ($al > $bl) ? +1 : -1;
}
}
$a[] = new TestObj("c");
$a[] = new TestObj("b");
$a[] = new TestObj("d");
usort($a, array("TestObj", "cmp_obj"));
foreach ($a as $item) {
echo $item->name . "\n";
}
?>
以上例程会输出：
b
c
d
Example #4 usort() example using a closure to sort a multi-dimensional array
'z', 'key_b' => 'c');
$array[1] = array('key_a' => 'x', 'key_b' => 'b');
$array[2] = array('key_a' => 'y', 'key_b' => 'a');
function build_sorter($key) {
return function ($a, $b) use ($key) {
return strnatcmp($a[$key], $b[$key]);
};
}
usort($array, build_sorter('key_b'));
foreach ($array as $item) {
echo $item['key_a'] . ', ' . $item['key_b'] . "\n";
}
?>
以上例程会输出：
y, a
x, b
z, c
参见
• uasort() - 使用用户自定义的比较函数对数组中的值进行排序并保持索引关联
• 数组排序函数对比
User Contributed Notes 58 notes
===============================================================================
When trying to do some custom sorting with objects and an anonymous function it
wasn't entirely clear how this usort function works. I think it probably uses a
quicksort in the background. Basically it actually moves the $b variable up or
down in respect to the $a variable. It does NOT move the $a variable inside the
callback function. This is key to getting your logic right in the comparisons.
If you return -1 that moves the $b variable down the array, return 1 moves $b
up the array and return 0 keeps $b in the same place.
To test I cut down my code to sorting a simple array from highest priority to
lowest.
$b)
{
echo "a ($a) is higher priority than b ($b), moving b down array\n";
return -1;
}
else {
echo "b ($b) is higher priority than a ($a), moving b up array\n";
return 1;
}
});
echo "Sorted priorities:\n";
var_dump($priorities);
?>
Output:
b (8) is higher priority than a (3), moving b up array
b (5) is higher priority than a (3), moving b up array
b (7) is higher priority than a (3), moving b up array
a (3) is same priority as b (3), keeping the same
a (8) is higher priority than b (3), moving b down array
b (8) is higher priority than a (7), moving b up array
b (8) is higher priority than a (5), moving b up array
b (8) is higher priority than a (3), moving b up array
a (5) is higher priority than b (3), moving b down array
a (7) is higher priority than b (5), moving b down array
Sorted priorities:
array(5) {
[0]=> int(8)
[1]=> int(7)
[2]=> int(5)
[3]=> int(3)
[4]=> int(3)
}
===============================================================================
This will sort subnets correctly:
$b_arr[$i] ) {
return 1;
}
}
return -1;
}
usort($zones, 'sort_subnets');
print '
';
print_r($zones);
print '
';
?>
===============================================================================
I wrote a wrapper for usort that lets you use something similar to an SQL ORDER
BY clause. It can sort arrays of associative arrays and arrays of objects and I
think it would work with some hybrid case.
Example of how the function works:
1, 'b' => 2, 'c' => 3),
array('a' => 2, 'b' => 1, 'c' => 3),
array('a' => 3, 'b' => 2, 'c' => 1),
array('a' => 1, 'b' => 3, 'c' => 2),
array('a' => 2, 'b' => 3, 'c' => 1),
array('a' => 3, 'b' => 1, 'c' => 2)
);
Utility::orderBy($testAry, 'a ASC, b DESC');
//Result:
$testAry = array(
array('a' => 1, 'b' => 3, 'c' => 2),
array('a' => 1, 'b' => 2, 'c' => 3),
array('a' => 2, 'b' => 3, 'c' => 1),
array('a' => 2, 'b' => 1, 'c' => 3),
array('a' => 3, 'b' => 2, 'c' => 1),
array('a' => 3, 'b' => 1, 'c' => 2)
);
?>
To sort an array of objects you would do something like:
Utility::orderBy($objectAry, 'getCreationDate() DESC, getSubOrder() ASC');
This would sort an array of objects that have methods getCreationDate() and
getSubOrder().
Here is the function:
1, 'asc' => -1);
$def = $ascending ? -1 : 1;
$keyAry = array();
$dirAry = array();
foreach($keys as $key) {
$key = explode(' ', trim($key));
$keyAry[] = trim($key[0]);
if(isset($key[1])) {
$dir = strtolower(trim($key[1]));
$dirAry[] = $dirMap[$dir] ? $dirMap[$dir] : $def;
} else {
$dirAry[] = $def;
}
}
$fnBody = '';
for($i = count($keyAry) - 1; $i >= 0; $i--) {
$k = $keyAry[$i];
$t = $dirAry[$i];
$f = -1 * $t;
$aStr = '$a[\''.$k.'\']';
$bStr = '$b[\''.$k.'\']';
if(strpos($k, '(') !== false) {
$aStr = '$a->'.$k;
$bStr = '$b->'.$k;
}
if($fnBody == '') {
$fnBody .= "if({$aStr} == {$bStr}) { return 0; }\n";
$fnBody .= "return ({$aStr} < {$bStr}) ? {$t} : {$f};\n";
} else {
$fnBody = "if({$aStr} == {$bStr}) {\n" . $fnBody;
$fnBody .= "}\n";
$fnBody .= "return ({$aStr} < {$bStr}) ? {$t} : {$f};\n";
}
}
if($fnBody) {
$sortFn = create_function('$a,$b', $fnBody);
usort($ary, $sortFn);
}
}
}
?>
===============================================================================
As the manual says, "If two members compare as equal, their order in the sorted
array is undefined." This means that the sort used is not "stable" and may
change the order of elements that compare equal.
Sometimes you really do need a stable sort. For example, if you sort a list by
one field, then sort it again by another field, but don't want to lose the
ordering from the previous field. In that case it is better to use usort with a
comparison function that takes both fields into account, but if you can't do
that then use the function below. It is a merge sort, which is guaranteed O
(n*log(n)) complexity, which means it stays reasonably fast even when you use
larger lists (unlike bubblesort and insertion sort, which are O(n^2)).
===============================================================================
this is a new multisort function for sorting on multiple subfield like it will
be in sql : 'ORDER BY field1, field2'
number of sort field is undefined
3, 'code'=>1);
$array[] = array('soc' => 2, 'code'=>1);
$array[] = array('soc' => 1, 'code'=>1);
$array[] = array('soc' => 1, 'code'=>1);
$array[] = array('soc' => 2, 'code'=>5);
$array[] = array('soc' => 1, 'code'=>2);
$array[] = array('soc' => 3, 'code'=>2);
//usage
print_r(multiSort($array, 'soc', 'code'));
function multiSort() {
//get args of the function
$args = func_get_args();
$c = count($args);
if ($c < 2) {
return false;
}
//get the array to sort
$array = array_splice($args, 0, 1);
$array = $array[0];
//sort with an anoymous function using args
usort($array, function($a, $b) use($args) {
$i = 0;
$c = count($args);
$cmp = 0;
while($cmp == 0 && $i < $c)
{
$cmp = strcmp($a[ $args[ $i ] ], $b[ $args[ $i ] ]);
$i++;
}
return $cmp;
});
return $array;
}
?>
output:
Array
(
[0] => Array
(
[soc] => 1
[code] => 1
)
[1] => Array
(
[soc] => 1
[code] => 1
)
[2] => Array
(
[soc] => 1
[code] => 2
)
[3] => Array
(
[soc] => 2
[code] => 1
)
[4] => Array
(
[soc] => 2
[code] => 5
)
[5] => Array
(
[soc] => 3
[code] => 1
)
[6] => Array
(
[soc] => 3
[code] => 2
)
)
===============================================================================
The easiest way to compare two integers is just to take the second away from
the first. For example, say you wanted to sort by an integer property of an
object. Your comparison function would look like this:
count - $b->count;
}
?>
This works because you don't necessarily have to return -1, 0 or 1, the manual
states any integer less than, equal to or greater than 0 is OK.
===============================================================================
If you want to sort an array according to another array acting as a priority
list, you can use this function.
$value)
{
if($a==$value)
{
return 0;
break;
}
if($b==$value)
{
return 1;
break;
}
}
}
$order[0] = "first";
$order[1] = "second";
$order[2] = "third";
$array[0] = "second";
$array[1] = "first";
$array[2] = "third";
$array[3] = "fourth";
$array[4] = "second";
$array[5] = "first";
$array[6] = "second";
usort($array, "listcmp");
print_r($array);
?>
===============================================================================
sort multi-dimentional arrays in class with usort
arr = $arr;
}
public function doSort()
{
$cmp = function($a, $b)
{
//Do Some Comparation
}
if(is_array($this->arr))
{
usort($this->arr, $cmp);
}
return $this->arr;
}
}
?>
===============================================================================
This lets you sort an associative multi-dimensional array by multiple key/field
names. Much similiar to the SQL clause ORDER BY. Enjoy.
'd',
'type' => 'a',
'name' => 'a'
);
while(list($key, $val) = each($vals)) {
if($val == "d") {
if ($a["$key"] > $b["$key"]) {
return -1;
}
if ($a["$key"] < $b["$key"]) {
return 1;
}
}
if($val == "a") {
if ($a["$key"] < $b["$key"]) {
return -1;
}
if($a["$key"] > $b["$key"]) {
return 1;
}
}
}
}
?>
===============================================================================
For using usort inside a method in an object, where the callback sort method is
in the same object, this works:
If you wish to keep elements in their original or reverse order if they are the
same length, just don't return zero for items that compare the same. Return a 1
or -1, as appropriate.
===============================================================================
This function will sort on more then one values, test and have fun
strtolower($b["' . $sort[$key]['name'] . '"])) { return (strtolower($a["' .
$sort[$key]['name'] . '"]) ';
} else {
$function .= 'if ($a["' . $sort[$key]['name'] . '"]<>$b["' . $sort[$key
]['name'] . '"]) { return ($a["' . $sort[$key]['name'] . '"] ';
}
if (isset($sort[$key]['sort'])&&($sort[$key]['sort'] == "DESC")) {
$function .= '<';
} else {
$function .= '>';
}
if (isset($sort[$key]['case'])&&($sort[$key]['case'] == TRUE)) {
$function .= ' strtolower($b["' . $sort[$key]['name'] . '"])) ? 1 : -1;
} else';
} else {
$function .= ' $b["' . $sort[$key]['name'] . '"]) ? 1 : -1; } else';
}
}
$function .= ' { return 0; }';
usort($array, create_function('$a, $b', $function));
}
?>
===============================================================================
I needed a sort method that would sort strings but take note of any numbers and
would compare them as number. I also want to ignore any non alphanumerical
characters.
Eg.
Slot 1 Example
Slot 10 Example
Slot 2 Example
Should infact be
Slot 1 Example
Slot 2 Example
Slot 10 Example
0) {
return 1;
}
}
return count($a) - count($b);
}
?>
===============================================================================
An even better implementation of osort [than my original, posted on 24-AUG-09
(since deleted)], allowing for multiple properties and directions. With php
5.3.0 sorting by properties of an object becomes MUCH simpler. Note that this
uses anonymous functions / closures. Might find reviewing the php docs on that
useful. Look below for examples for previous version of php.
true);
usort($array, function($a, $b) use ($props) {
foreach($props as $prop => $ascending)
{
if($a->$prop != $b->$prop)
{
if($ascending)
return $a->$prop > $b->$prop ? 1 : -1;
else
return $b->$prop > $a->$prop ? 1 : -1;
}
}
return -1; //if all props equal
});
}
?>
Usage:
true, "Size" => false));
//or
osort($items, "Color");
?>
===============================================================================
If you need to use usort with a key in the calling method, I wrote this as a
utility:
obj = $obj;
$this->method = $method;
$this->key = $key;
}
function sort($a, $b) {
return call_user_func_array(array($this->obj, $this->method), array($a,
$b, $this->key));
}
}
?>
$key, $b->$key);
}
}
class FooBar {
public $item;
function __construct($val) {
$this->item = $val;
}
}
?>
~ simple example... but in the way I need to use it was the key was used in a
switch statement to choose the different member of the object to compare
against dynamically (as in, sort by x or y or z)
===============================================================================
$property))
// make sure requested property is correct for the object
{
$this->property = $property;
usort($objects_array, array($this,'_compare'));
}
else
{
$this->sorted = false;
return;
}
}
else
{
list($property,$var) = each($sample);
$this->property = $property;
usort($objects_array, array($this,'_compare'));
}
$this->sorted = ($objects_array);
}
function _compare($apple, $orange)
{
$property = $this->property;
if ($apple->$property == $orange->$property) return 0;
return ($apple->$property < $orange->$property) ? -1 : 1;
}
} // end class
?>
USAGE EXAMPLE
DUMP ORIGINAL
user Object ( [name] => Yunihe Jopoba [age] => 27 [richness] => â‚¬ 899,970 )
user Object ( [name] => Janirevi Fakejorumoa [age] => 19 [richness] => â‚¬
219,078 )
user Object ( [name] => Korejowi Mezede [age] => 95 [richness] => â‚¬ 3,272 )
user Object ( [name] => Nugoaivu Jongyi [age] => 84 [richness] => â‚¬ 94,853 )
user Object ( [name] => Cepomase Buaesukoyua [age] => 32 [richness] => â‚¬
677,180 )
user Object ( [name] => Vejosehona Auva [age] => 20 [richness] => â‚¬ 144,540 )
user Object ( [name] => Fewame Wojuvuzo [age] => 69 [richness] => â‚¬ 198,231 )
user Object ( [name] => Risuku Zagedobu [age] => 48 [richness] => â‚¬ 763,860 )
user Object ( [name] => Fazurada Aayu [age] => 16 [richness] => â‚¬ 302,352 )
SORTED by age
sorted)
{
$objects_array = $objects->sorted;
foreach ($objects_array as $key=>$object) { print_r($object); echo "
"; }
}
?>
user Object ( [name] => Fazurada Aayu [age] => 16 [richness] => â‚¬ 302,352 )
user Object ( [name] => Janirevi Fakejorumoa [age] => 19 [richness] => â‚¬
219,078 )
user Object ( [name] => Vejosehona Auva [age] => 20 [richness] => â‚¬ 144,540 )
user Object ( [name] => Yunihe Jopoba [age] => 27 [richness] => â‚¬ 899,970 )
user Object ( [name] => Cepomase Buaesukoyua [age] => 32 [richness] => â‚¬
677,180 )
user Object ( [name] => Risuku Zagedobu [age] => 48 [richness] => â‚¬ 763,860 )
user Object ( [name] => Fewame Wojuvuzo [age] => 69 [richness] => â‚¬ 198,231 )
user Object ( [name] => Nugoaivu Jongyi [age] => 84 [richness] => â‚¬ 94,853 )
user Object ( [name] => Korejowi Mezede [age] => 95 [richness] => â‚¬ 3,272 )
SORTED by richness
sorted)
{
$objects_array = $objects->sorted;
foreach ($objects_array as $key=>$object) { print_r($object); echo "
"; }
}
?>
user Object ( [name] => Vejosehona Auva [age] => 20 [richness] => â‚¬ 144,540 )
user Object ( [name] => Fewame Wojuvuzo [age] => 69 [richness] => â‚¬ 198,231 )
user Object ( [name] => Janirevi Fakejorumoa [age] => 19 [richness] => â‚¬
219,078 )
user Object ( [name] => Korejowi Mezede [age] => 95 [richness] => â‚¬ 3,272 )
user Object ( [name] => Fazurada Aayu [age] => 16 [richness] => â‚¬ 302,352 )
user Object ( [name] => Cepomase Buaesukoyua [age] => 32 [richness] => â‚¬
677,180 )
user Object ( [name] => Risuku Zagedobu [age] => 48 [richness] => â‚¬ 763,860 )
user Object ( [name] => Yunihe Jopoba [age] => 27 [richness] => â‚¬ 899,970 )
user Object ( [name] => Nugoaivu Jongyi [age] => 84 [richness] => â‚¬ 94,853 )
Simulated wrong property request ( dumb property )
sorted)
{
$objects_array = $objects->sorted;
foreach ($objects_array as $key=>$object) { print_r($object); echo "
"; }
}
else echo 'DUMB ERROR';
?>
DUMB ERROR
===============================================================================
Here's how you can usort() a multidimensional array (like in example #2 above)
within a class:
===============================================================================
The sample function for having the sort function be a class method has a
comment identifying the sorting function as static, however the function does
not have the static keyword. In PHP 5 (at least as configured on my server),
usort will fail, identifying the method as non-static. Preceding the function
keyword with the static keyword fixed the problem.
===============================================================================
usort returns null when the sorting function is not (yet) defined. The function
has to be defined before usort is called, afterwards doesn't work.
===============================================================================
Sorting a multidimensional array by a subkey seem to be one of the bigger
challenges when using usort. At least if one want the key to be dynamic. For
anyone interested this code seemed to work rather well for me:
key = $key;
}
function cmp__($a,$b) {
$key = $this->key;
if ($a[$key] == $b[$key]) return 0;
return (($a[$key] > $b[$key]) ? 1 : -1);
}
}
?>
===============================================================================
Just something i stumbled about right now:
If the array consists of just one elemtent, the user-function is not called at
all.
Although this surely makes sense, think of it if you want to use your
order-function for adding extra data to your arrays...
===============================================================================
here's another recursive multisort, however a clean and fast one that is
class-based (but works as well outside classes) and does not uglify your global
namespace at all. note that strnatcmp is used, but one could use something else
of course.
btw, for arrays in which the rows/columns are 'swapped', use array_multisort().
aSortkeys[$i]],$b[$this->aSortkeys[$i]]);
if($r==0) {
$i++;
if ($this->aSortkeys[$i]) $r = $this->_sortcmp($a, $b, $i+1);
}
return $r;
}
function sort() {
if(count($this->aSortkeys)) {
usort($this->aData,array($this,"_sortcmp"));
}
}
}
$B = new Banana;
$B->aData = array(
array("name" => "hank", "headsize" => "big", "age" => 32),
array("name" => "frank", "headsize" => "huge", "age" => 36)
);
$B->aSortkeys = array("age","name");
$B->sort();
?>
sorry for the ugly indenting, but i couldn't get it any better in this note
adder thing.
===============================================================================
Here is a simple example of converting a timestamp date("U") into a date. This
sorts by that day and then by string value alphabetically.
I hope it saves someone some time... Happy PHP'in!
";
}
?>
This will output:
$shared[0]:<PHONE_NUMBER> username: alvin
$shared[1]:<PHONE_NUMBER> username: larry
$shared[2]:<PHONE_NUMBER> username: garth
$shared[3]:<PHONE_NUMBER> username: harvy
===============================================================================
I'd like to share with the community my function for sorting an array of arrays
or objects containing associative data. This could be used, for example, with a
MySQL result.
0) && ( ( is_array($arr[0]) && isset($arr
[0][$field]) ) || ( is_object($arr[0]) && isset($arr[0]->$field) ) ) ){
if($case_insensitive==true) $strcmp_fn = "strnatcasecmp";
else $strcmp_fn = "strnatcmp";
if($sorting==SORT_ASC){
$fn = create_function('$a,$b', '
if(is_object($a) && is_object($b)){
return '.$strcmp_fn.'($a->'.$field.', $b->'.$field.');
}else if(is_array($a) && is_array($b)){
return '.$strcmp_fn.'($a["'.$field.'"], $b["'.$field.'"]);
}else return 0;
');
}else{
$fn = create_function('$a,$b', '
if(is_object($a) && is_object($b)){
return '.$strcmp_fn.'($b->'.$field.', $a->'.$field.');
}else if(is_array($a) && is_array($b)){
return '.$strcmp_fn.'($b["'.$field.'"], $a["'.$field.'"]);
}else return 0;
');
}
usort($arr, $fn);
return true;
}else{
return false;
}
}
?>
===============================================================================
To sort reliably on more than one "column" in database-style arrays, handle
this within your cmp function where the first field to be sorted returns 0:
$b[field_2]){
return -1;
}
elseif($a[field_2] < $b[field_2]){
return 1;
}
}
elseif($a[field_1] > $b[field_1]){
return -1;
}
elseif($a[field_1] < $b[field_1]){
return 1;
}
}
?>
Sorting by doing multiple passes does not seem to be reliable.
===============================================================================
Needed a quick, fairly uncluttered way of sorting an array of objects by a
certain object attribute, so here's what I came up with. Uses one global array
and usort(). Also accepts an optional sort direction argument (CSORT_ASC = sort
ascending, CSORT_DESC = sort descending).  Probably a better way to pull this off, but
this works alright.
$csort_cmp['key'] > $b->$csort_cmp['key'])
return $csort_cmp['direction'];
if ($a->$csort_cmp['key'] < $b->$csort_cmp['key'])
return -1 * $csort_cmp['direction'];
return 0;
}
function csort(&$a, $k, $sort_direction=CSORT_ASC)
{
global $csort_cmp;
$csort_cmp = array(
'key' => $k,
'direction' => $sort_direction
);
usort($a, "csort_cmp");
unset($csort_cmp);
}
?>
===============================================================================
You can also sort multi-dimensional array for multiple values like as
"Sally",
"nick_name"=> "sal",
"availability"=> "0",
"is_fav"=> "0"
],
[
"name"=> "David",
"nick_name"=> "dav07",
"availability"=> "0",
"is_fav"=> "1"
],
[
"name"=> "Zen",
"nick_name"=> "zen",
"availability"=> "1",
"is_fav"=> "0"
],
[
"name"=> "Jackson",
"nick_name"=> "jack",
"availability"=> "1",
"is_fav"=> "1"
],
[
"name"=> "Rohit",
"nick_name"=> "rod",
"availability"=> "0",
"is_fav"=> "0"
],
];
usort($arr,function($a,$b){
$c = $b['is_fav'] - $a['is_fav'];
$c .= $b['availability'] - $a['availability'];
$c .= strcmp($a['nick_name'],$b['nick_name']);
return $c;
});
print_r($arr);
?>
Output:
Array
(
[0] => Array
(
[name] => Jackson
[nick_name] => jack
[availability] => 1
[is_fav] => 1
)
[1] => Array
(
[name] => David
[nick_name] => dav07
[availability] => 0
[is_fav] => 1
)
[2] => Array
(
[name] => Zen
[nick_name] => zen
[availability] => 1
[is_fav] => 0
)
[3] => Array
(
[name] => Rohit
[nick_name] => rod
[availability] => 0
[is_fav] => 0
)
[4] => Array
(
[name] => Sally
[nick_name] => sal
[availability] => 0
[is_fav] => 0
)
)
===============================================================================
As the documentation says, the comparison function needs to return an integer
that is either "less than, equal to, or greater than zero". There is no
requirement to restrict the value returned to -1, 0, 1.
integer_property > $b->integer_property) {
return 1;
}
elseif($a->integer_property < $b->integer_property) {
return -1;
}
else {
return 0;
}
});
?>
can be simplified to
integer_property - $b->integer_property;
});
?>
This of course applies to any comparison function that calculates an integer
"score" for each of its arguments to decide which is "greater".
===============================================================================
Below is a variation on Example #4 that implements a multi-key natural sort on
an associative array and can be called in such a way as to allow reversing the
sort order and/or making the comparison case insensitive on a key by key basis.
Test code is included in the file – run it from the command line with: php
sortUtils.php
'In Progress', 'comment'=>'This looks good.',
'user_name'=>'John Doe', 'date_modified'=>'06/13/2014 11:20 AM', 'role'=>
'Senior Account Manager');
$test[] = array('Status'=>'In Progress', 'comment'=>'This looks good,
please approve.', 'user_name'=>'John Doe', 'date_modified'=>'06/13/2014 11:19
AM', 'role'=>'Account Manager');
$test[] = array('Status'=>'In Progress', 'comment'=>'This looks good.',
'user_name'=>'Jane Smith', 'date_modified'=>'06/13/2014 11:19 AM', 'role'=>
'Senior Account Manager');
$test[] = array('Status'=>'Returned', 'comment'=>'There is not enough
informartion. Please add the following.', 'user_name'=>'John Doe',
'date_modified'=>'06/13/2014 11:15 AM', 'role'=>'Account Manager');
$test[] = array('Status'=>'In Progress', 'comment'=>'I am currently
reviewing this.', 'user_name'=>'John Doe', 'date_modified'=>'06/13/2014 11:14
AM', 'role'=>'Account Manager');
echo "Original array: ";
print_r($test);
echo "Sorted on date_modified: ";
mknatsort($test, array('date_modified') );
print_r($test);
echo "Sorted on role(reversed) & date_modified: ";
mknatsort($test, array('role','date_modified'),array(true,false) );
print_r($test);
echo "Sorted on role & date_modified(reversed): ";
mknatsort($test, array('role','date_modified'),array(false,true) );
print_r($test);
}
?>
===============================================================================
This comment is just to help backward compatibility.
I needed to have a foreach loop using reference just before using the usort
function on the same array that was used in the foreach.
Like this:
_arrSubCat))
return false;
foreach($this->_arrSubCat as &$cat)
$cat->sortByTitle();
usort($this->_arrSubCat, 'strcasecmp');
}
?>
I had this strange bug where the last object of the $this->_arrSubCat array
before the sort was alway replaced/overwrited with his string value.
On my machine (PHP 5.3), I had no problem, but when I placed the code on
another server, my code crashed with a fatal error (Because I was using a
string as an object later in the code)
The solution I found is really simple, and avoid the array to have a reference
declared in memory while running the sort function. Just add an unset($cat):
_arrSubCat))
return false;
foreach($this->_arrSubCat as &$cat)
$cat->sortByTitle();
unset($cat); //No more problem because of the foreach &cat reference.
usort($this->_arrSubCat, 'strcasecmp');
}
?>
It took me an hour an a half to locate the bug, hope it will save someone some
time !
===============================================================================
If you ever have to sort a collection of objects on something like a string
(name) present in every object, but want to keep the array of objects intact
you might find this useful:
name, $b->name);
}
usort($objectArray, "naturalSortByName");
return $objectArray;
}
?>
===============================================================================
Remember that functions inside of functions will become part of the global
scope too. So, something like:
$b;
}
usort($array, "compare");
return $array;
}
foo($something);
bar($something_else);
?>
Will result in a fatal error because you're redeclaring 'compare'. This could
be a little strange, e.g. for JavaScript programmers who expect functions in
functions to become private outside of the parent scope.
===============================================================================
I see many people here (including the official examples) write their callbacks
rather clumsily like this:
Or if they are a bit more clever:
But this can by simplified further to:
===============================================================================
Here's how to use usort() within a class using a static function as a callback
(using the example above):
name = $name;
usort($this->name, array(&$this, "compareValues"));
}
static function compareValues($a, $b){
$al = strtolower($a->name);
$bl = strtolower($b->name);
if ($al == $bl) {
return 0;
}
return ($al > $bl) ? +1 : -1;
}
}
?>
===============================================================================
{$on},\$b->{$on});"
: "return strcmp(\$a->{$on},\$b->{$on});";
usort($objects, create_function('$a,$b', $comparer));
}
?>
===============================================================================
strcmp (or strcasecmp) can be used as a callback function for usort. It will
cast your comparison values to string. Thus, you can implement a __toString()
method into your classes and use usort without creating a callback function:
a = $a;
$this->b = $b;
}
public function __toString() {
return (string)$this->a;
}
}
$foo = array(new Foo('t', 'b'), new Foo('a', 'c'), new Foo('g', 'd'));
print_r($foo);
usort($foo, 'strcasecmp');
print_r($foo);
?>
===============================================================================
Needed to sort an array of objects based on multiple properties. (ie: Group,
then Last Name, then First Name) Doing this in multiple usorts fails because
the second usort ends up shuffling the results of the previous usort because
order is undefined when criteria are equal. Ended up writing a function that
builds a comparison operator by nesting ternary operators for each field, then
using that function in usort(). Hopefully it's of use to someone else.
'getPrice()', order=>'ASC', 'comparer'=>'number'),
* array('property'=>'getName()', order=>'DESC', 'comparer'=>'string'),
* array('property'=>'created_date', order=>'ASC', 'comparer'=>'date'),
* array('property'=>'id', order=>'ASC', 'comparer'=>'number'),
* ));
*
* @author Tyler Chamberlain
*/
function sortObjectsByProperties(&$objects, $fields) {
$comparerFunctionString = "";
foreach ($fields as $field) {
if ($field['comparer'] == 'number') {
$comparerFunction = "(\$a->{$field['property']} == \$b->{$field
['property']} ? 0 : (\$a->{$field['property']} > \$b->{$field['property']} ? 1
: -1))";
} elseif ($field['comparer'] == 'date') {
$comparerFunction = "(strtotime(\$a->{$field['property']}) >
strtotime(\$b->{$field['property']}) ? 1 : -1)";
} else {
$comparerFunction = "strcasecmp(\$a->{$field['property']},\$b->
{$field['property']})";
}
if ($field['order'] === 'DESC') { $comparerFunction = "-".
$comparerFunction; }
$comparerFunctionString .= "$comparerFunction != 0 ?
$comparerFunction : (";
}
$comparer = "return ($comparerFunctionString 0 )".str_repeat(")",
sizeof($fields)).";";
usort($objects, create_function('$a,$b', $comparer));
}
?>
===============================================================================
In order to get a proper text sorting I have changed the arfsort() function
submitted by jonathan(at)inetz(dot)com.
The one line I have changed is:
to
It can now sort correctly for alphabetization. Capital letters where getting
in the way.
Sean
===============================================================================
When I query a DB I usually put my record set inside of a multi-dimentional
array. I finally wrote a program that will allow you to sort your record set
by column after you put it in an array.
$sorted[$j+1][$column]) {
$tmp = $sorted[$j];
$sorted[$j] = $sorted[$j+1];
$sorted[$j+1] = $tmp;
}
}
return $sorted;
}
?>
===============================================================================
Now, in php 7, we can use the spaceship operator. For example lest sort array
of words from element string length:
strlen($b);
});
===============================================================================
The usort function actually moves $b up when the callback function returns both
0 and 1. If you want to preserve the original order in the array, return 1
when $a == $b instead of 0. Try this code below to see how usort alters the
order of the original array when all values are the same.
name = $name;
$this->id = $id;
}
static function cmp_obj($a, $b) {
$al = strtolower($a->name);
$bl = strtolower($b->name);
if ($al == $bl) {
return 0; // return 1 if you don't want $b to go in front of $a
}
return ($al > $bl) ? +1 : -1;
}
}
$a[] = new TestObj("a", 1);
$a[] = new TestObj("a", 2);
$a[] = new TestObj("a", 3);
var_dump($a);
usort($a, array("TestObj", "cmp_obj"));
var_dump($a);
?>
===============================================================================
The array_alternate_multisort function written by robert below doesn't work.
There are several bugs in the code and it doesn't work when sorting by multiple
keys because the order of the first key isn't taken into account when sorting
by the second key and so on. Also, because robert uses strcasecmp the algorithm
doesn't work properly with floats or other variable types. Here's the improved
version:
===============================================================================
If you want to sort an array of strings by the length of its values, you can
write a better cmp-function than manually comparing string lengths with
if-statements. Unfortunately, I see this bad technique in other people's code.
I prefer using this:
This function sorts the array in ascending order. If you want to sort
descending, simply swap $a and $b either in the parameters or in the
subtraction.
-Tim
===============================================================================
Another way to compare object is to have a compare static function in the class
with reccursion ability and have globals or static variables who save the state
of comparison, and the order.
It could be a good idea to have a variable with comparison functions name (with
the sorting : numeric, alphanumeric, inverse).
var1=$v1; $this->var2=$v2; $this->var3=$v3;
}
public function __toString() {
return "v1 ".$this->var1." v2 ".$this->var2." v3 ".$this->var3;
}
static function compare($a, $b){
$sort=$GLOBALS['sorts'][$GLOBALS['sort']];
echo "$sort\n";
if($a->$sort == $b->$sort){
if($GLOBALS['sorts'][$GLOBALS['sort']+1]){
$GLOBALS['sort']++;
$res= call_user_func(array('myObj', 'compare'
), $a, $b);
$GLOBALS['sort']=0; return $res;
}
$GLOBALS['sort']=0; return 0;
}
$GLOBALS['sort']=0;
if($a->$sort > $b->$sort)
return 1;
return -1;
}
}
$objects = array(new myObj("1", "2", "3"), new myObj("2", "2", "2"), new myObj(
"1", "3", "4"));
/* Tests */
$sorts=Array('var1', 'var2', 'var3'); $sort = 0; usort($objects, array('myObj',
'compare')); echo ("var1 var2 var3\n"); foreach($objects as $o)echo $o."\n";
$sorts=Array('var2', 'var3', 'var1'); $sort = 0; usort($objects, array('myObj',
'compare')); echo ("\nvar2 var3 var1\n"); foreach($objects as $o)echo $o."\n";
$sorts=Array('var2', 'var1', 'var3'); $sort = 0; usort($objects, array('myObj',
'compare')); echo ("\nvar2 var1 var3\n"); foreach($objects as $o)echo $o."\n";
?>
===============================================================================
If you want to sort the time based array, then this will be helpfull.
function timesort($array){
usort($array, function($a, $b)
{
$a=strtotime($a);
$b=strtotime($b);
if ($a == $b)
{
return 0;
}
else if ($a < $b)
{
return -1;
}
else {
return 1;
}
});
}
Input:
$time_array=Array
(
[1] => 10:00AM
[2] => 09:00AM
[3] => 02:00PM
[4] => 11:00AM
)
Output:
print_r(timesort($time_array));
Array
(
[0] => 09:00AM
[1] => 10:00AM
[2] => 11:00AM
[3] => 02:00PM
)
===============================================================================
Instead of doing :
you could do this :
which is more efficient and is does case insensitive comparison according to
the current locale.
===============================================================================
For sort multi-array by specific index
===============================================================================
Needed a date sort and I didn't know if one was available so I wrote one. Maybe
it'll help someone:
$d is the delimeter
===============================================================================
If you've used ADO before, you may have used the Sort property on a recordset.
It's very powerful - you can add a nice ORDER BY clause after getting the
recordset from the database. It's especially helpful if you want to show a
list on a web page and make the column headings links that cause the list to
resort on that column.
I wanted to do the same thing with mysql recordsets, but it looks like you have
to have the ORDER BY in your query. I re-worked the example from johan_land at
yahoo dot com above for sorting multidimensional arrays. When I get a mysql
recordset, I create an array with all of the records like this:
0)
while ($aRow = mysql_fetch_array($rsRows, MYSQL_ASSOC))
$aaRows[] = $aRow;
?>
At this point $aaRows is an array of arrays - it's a numeric-indexed array
containing records from the recordset, which themselves are associative
arrays. The following code takes the array of records as the first parameter,
and an array of fields to sort - each field is an associative array, where
'name' is the db field name, and 'dir' is the direction to sort. If dir is
'DESC' (case-insensitive), it will sort descending. Any other value (including
not setting one) will cause it to sort ascending.
$vValue2 ? 1 : -1;
if (strtolower(substr($sSortFieldDir, 0, 4)) == 'desc')
$lCompareVal = -$lCompareVal;
}
}
return $lCompareVal;
}
$g_aaSortArray = $a_aaSortCriteria;
usort($a_aaRows, 'compare');
}
?>
When I call it it looks something like this:
'STATE', 'dir' => 'ASC'), array('name'
=> 'CITY', 'dir' => 'DESC')));
?>
===============================================================================
Example 3 above does not work with 4.0.4pl1, unless you write the uasort line
as follows:
uasort($a, array ($a[0], "cmp_obj"));
(I assume any instance of the object: a[0] or a[1] or a[2] would work as well)
It does not work at all with associative arrays of objects.
===============================================================================
These functions will sort an array by more than one element. The elements to
sort by is specified in $sortArr. If you eg. want to sort by $destArr[]
["sortBy2"][0] you add '["sortBy2"][0]' to $sortArr. Use it as much as you
want!! If you modify it, please let me know...
$bvalue) ? (1) : (-1);
}
}
//For testing the functions
$destArr = array( array( "sortBy1" => 2, "sortBy2" => array( "Fish", "eat
seafood" )), array( "sortBy1" => 1, "sortBy2" => array( "Lions", "eat
everything" )), array( "sortBy1" => 1, "sortBy2" => array( "Bird", "eat
birdfood" )) );
$sortArr = array( '["sortBy1"]', '["sortBy2"][0]' );
print_r($destArr);
usort($destArr, "compare");
reset($destArr);
print_r($destArr);
?>
===============================================================================
To sort multidimentional arrays .... by one key.
$b["'.$key.'"]) ? -1 : 1;}');
usort($tab,$compare) ;
return $tab ;
}
?>
===============================================================================
array('category_id'=>1,'parent_id' =>3,'category_name' =>
'Second Child','category_position'=>2),
1=>array('category_id' =>2,'parent_id' =>0,'category_name'
=>'Second Parent','category_position'=>2),
2=>array('category_id' =>3,'parent_id' =>0,'category_name'
=>'First Parent','category_position'=>1),
3=>array('category_id' =>4,'parent_id' =>0,'category_name'
=>'Third Parent','category_position'=>3),
4=>array('category_id' =>5,'parent_id' =>3,'category_name'
=>'First Child','category_position'=>1),
5=>array('category_id' =>6,'parent_id' =>5,'category_name'
=>'Second Sub-Child','category_position'=>2),
6=>array('category_id' =>7,'parent_id' =>5,'category_name'
=>'First Sub-Child','category_position'=>1)
);
$ordered = chain('category_id', 'parent_id', 'category_position', $rows);
foreach($ordered as $item)
{
echo str_repeat('------', $item['indent']).$item['category_name'].'
';
}
/*
Output
First Parent
------First Child
------------First Sub-Child
------------Second Sub-Child
------Second Child
Second Parent
Third Parent
You can have it only return a certain "branch" if you specify a root_id.
Aditionally, you can keep it by going to deep by specifying max-level.
Hope someone finds this useful, I sure would have liked to see this here a week
ago.
Ah yes... and the code that runs it.
*/
function chain($primary_field, $parent_field, $sort_field, $rows, $root_id=0,
$maxlevel=25)
{
$c = new chain($primary_field, $parent_field, $sort_field, $rows, $root_id,
$maxlevel);
return $c->chain_table;
}
class chain
{
var $table;
var $rows;
var $chain_table;
var $primary_field;
var $parent_field;
var $sort_field;
function chain($primary_field, $parent_field, $sort_field, $rows, $root_id,
$maxlevel)
{
$this->rows = $rows;
$this->primary_field = $primary_field;
$this->parent_field = $parent_field;
$this->sort_field = $sort_field;
$this->buildChain($root_id,$maxlevel);
}
function buildChain($rootcatid,$maxlevel)
{
foreach($this->rows as $row)
{
$this->table[$row[$this->parent_field]][ $row[$this->primary_field
]] = $row;
}
$this->makeBranch($rootcatid,0,$maxlevel);
}
function makeBranch($parent_id,$level,$maxlevel)
{
$rows=$this->table[$parent_id];
foreach($rows as $key=>$value)
{
$rows[$key]['key'] = $this->sort_field;
}
usort($rows,'chainCMP');
foreach($rows as $item)
{
$item['indent'] = $level;
$this->chain_table[] = $item;
if((isset($this->table[$item[$this->primary_field]])) && ((
$maxlevel>$level+1) || ($maxlevel==0)))
{
$this->makeBranch($item[$this->primary_field], $level+1,
$maxlevel);
}
}
}
}
function chainCMP($a,$b)
{
if($a[$a['key']] == $b[$b['key']])
{
return 0;
}
return($a[$a['key']]<$b[$b['key']])?-1:1;
}
?>
===============================================================================
The sort functions do nothing if identical keys exist. Of course, you
shouldn't have identical keys anyway, but this just might save someone else the
oodles of time it took me to figure out while using multi-dimentional arrays:
array ( "2", "3" ),
"articleList2" => array ( "3" , "4")
);
usort( $a, array( $this, "compareByTitle") );
// doesn't work
$b = array (
"articleList" => array ( "2", "3" ),
"articleList" => array ( "3" , "4")
);
usort( $b, array( $this, "compareByTitle") );
}
function compareByTitle( $a, $b ) {
// ... //
}
}
?>
===============================================================================
just for debugging purposes, usort does not complain if its argument function
is not defined, i.e.:
will not do anything...
===============================================================================
when using usort to refer to a function inside a class i have succesfully used:
===============================================================================
[The second version of a function I wrote], just a little cleaner to use, since
the usort call is now folded into the custom 'usortByArrayKey' function.
Seems like this is a popular problem - sorting an array of arrays by the keys
of sub-arrays, so I'll go ahead and throw in an approach I haven't seen anyone
mention yet. It only works since PHP 5.3 because that's when anonymous
functions got added to the language.
$sub_asc) {
//array can come as 'sort_key'=>SORT_ASC|SORT_DESC or just
'sort_key', so need to detect which
if(!in_array($sub_asc, $sort_flags)) { $sub_key = $sub_asc;
$sub_asc = $asc; }
//just like above, except 'continue' in place of return 0
if(!isset($a[$sub_key]) || !isset($b[$sub_key])) {
throw new Exception('attempting to sort on non-existent
keys');
}
if($a[$sub_key] == $b[$sub_key]) continue;
return ($sub_asc==SORT_ASC xor $a[$sub_key] < $b[$sub_key]) ? 1
: -1;
}
return 0;
}
};
usort($array, $cmp);
};
?>
Examples:
1) Sort a multi-dimensional array by a single key, from least to greatest:
usortByArrayKey($resultset, 'order_id');
2) Sort a multi-dimensional array by a single key, from greatest to least:
usortByArrayKey($resultset, 'purchase_amount', SORT_DESC);
3) Sort a multi-dimensional array first by one key, but then by a different key
when the first one is equal, both from least to greatest:
usortByArrayKey($resultset, array('product_id', 'price'));
4) Sort a multi-dimensional array by two different keys from least to greatest,
and then a third from greatest to least if the first two keys map to the equal
values:
usortByArrayKey($resultset, array('product_id', 'customer_id', 'date'=>
SORT_DESC));
5) Sort a multi-dimensional array by multiple keys, all from greatest to least:
usortByArrayKey($resultset, array('product_id', 'price'), SORT_DESC);
One word of caution, since SORT_ASC and SORT_DESC have actual int values of 4
and 3, respectively, if you need to sort a multi-dimensional array by keys 3 or
4, and you're using an array to pass in your keys, you MUST specify your sort
flags (e.g. array(3 => SORT_ASC,...)) to prevent unexpected behavior, instead
of relying on the function's second parameter as your default sort flag.
===============================================================================
For anyone else sorting mixed RSS feeds in date order, here's an example of the
perhaps not so obvious way of calling a method from the same class using usort
():
$b_t ) ? -1 : 1;
}
// assemble arrays for display in date order
function all_documents(){
$all_data = array_merge (
$this->upcoming(), $this->past() ) ;
// Use within its own class using the $this syntax so:
usort( $all_data, array( $this , "cmp_pubdate" ) ) ;
return $all_data ;
}
}
?>
As previously said, use as a static function in other parts of your code:
===============================================================================
I recommend that you take special note of the fact that an INTEGER value must
be returned from a sorting callback function. So, let's say you want to sort
arrays by a quotient of two of their elements and to do so you write something
like:
You may not get the result you want because probably $x['num']/$x['denom'] has
absolute value less than 1 and you'll get a lot of "same value" effective
results from the comparator function as integer rounding occurs.
To solve this just boost up the quotients to be big integers, then subtract
them:


{% extends 'DSSCDB/base.html' %} {% load static %} {% block content %}
The batch download will produce a flat structured CSV file. Note that this does not have the same structure as the batch upload file.


HAE-JI PARK
Hi! My name is Hae-Ji Park. (First name: Hae-Ji a.k.a HJ) I live in California, but I'm originally from South Korea. I am currently pursuing a B.S. in Computer Science at Oregon State University by taking courses online. My first degree was in Nursing. I worked as a Registered Nurse for one and a half years in South Korea. It was rewarding but learning how to code was much more fun. So I decided to change my career path. When I'm not coding, I like to bike, hike, go for a walk, and take photos.
PROJECTS
We Love Nature
[Personal Project (OSU CS361 Project)] "We Love Nature" - Reacting(Like or Dislike) to nature images by swiping left or right, or pressing a button, Seeing new set of nature images using my microservice-Nature Image Web Scraper (deployed by Google Cloud), Styling nature images
Nature Image Web Scraper
[Personal Project (OSU CS361 Project)] Nature Image Web Scraper using puppeteer. Returns nature image URLs. (/a-nature-image: Get only one nature image URL, /a-set-of-nature-images: Get about 8 nature image URLs at once.)
To-Do List
[Personal Project] To-Do List in React JS (Add, Check, Edit, Delete, Filter, Drag&Drop Tasks, etc.)
uQueue
[Team Project] A digital queuing application for small businesses. This is a submission for BeaverHacks Summer 2020 hackathon.
l worked on the front and back end: login, logout, creating new user/business profile, authentication(by using jsonwebtoken), encrypting password(by using bcrypt). I worked with JavaScript, Node.js, Express.js, mongoDB, Bootstrap, HTML5, CSS.
Make Your Korean Name
[Personal Project] A website to create user's Korean name, or pick one from the Korean name lists and provide learning Korean materials
Orbit Hunt
[Group project] A game trying to grab the green balls before being attacked by the red balls. This is a submission for Game Off 2019
SKILLS
Python3 / Pygame / Pandas / Numpy
HTML5 / CSS
JavaScript / React.js / Node.js / Express.js / puppeteer
MySQL / Mongo DB
Git
Korean (Native proficiency), English
INTERESTS
Cycling / Hiking / Traveling / Software Engineering / AI


MUM Golden Dome Market:::SRM System
Products
Supliers
Hello!
Sign Out
New Product
Product Number
name
Unit price
Quantity in stock
Supplier
Date Supplied
Enter a valid Date.

Reset

Cancel

Add Product
Product Value that you entered is below:
Number
Name
Price
Quantity
Supplier
Date


--- layout: post esbma_id: 1118 title: Ouch date: 2004-12-15 21:10:05 ---
How embarrassing! Roland Boon found a silly bug in the sample code in the MSDN article I posted yesterday. (I used a variable which was no longer in scope.)
 Even in fake code, always make sure it compiles before you check it in. :-)


httpd(n) 1.6 "Tcl Web Server"
httpd - HTTP protocol implementation
TABLE OF CONTENTS
SYNOPSIS
DESCRIPTION
Server Management
Connection Management
POST Management and Reading
Result Management and Generation
SEE ALSO
KEYWORDS
COPYRIGHT
package require httpd ?1.6?
The package httpd implements the server side of the HTTP
protocol and as such can be used as the core of any Tcl based web
server implementation. One such full-fledged web server is
tclhttpd.
Note: This package does not provide the ability to
register a callback when a request was received completely. It
dispatches all collected requests to the package httpd::url
instead. This package then provides an interface for the definition
and usage of a database mapping from urls to implementations,
i.e. Tcl commands handling them.
The API is divided into the following four categories, each described in
its own section.
Operations to handle the server at large.
- Httpd_Init
-
Initializes the internal data structures of the package. Has to be
called before Httpd_Server or Httpd_SecureServer. Some
of the others public commands of this package will call this
command on their own if it had not been called before.
- Httpd_Shutdown
-
A convenience command. It calls Httpd_ServerShutdown,
Httpd_SecureServerShutdown, and all callback commands
registered with the package through Httpd_RegisterShutdown.
The registered callbacks are called before the two shutdown commands
of this package. Any errors thrown by the callbacks are logged via the
package httpd::log, but ignored otherwise.
The result of the command is a boolean value. false signals to
the caller that at least one of the registered callbacks threw an
error.
- Httpd_RegisterShutdown cmd
-
Registers cmd as a callback which will be called when the server
is shutdown via Httpd_Shutdown. Errors thrown by cmd
during its invocation are logged, but otherwise ignored. Any result
returned by cmd is ignored]. The cmd is called without any
argument.
- Httpd_Server ?port? ?name? ?ipaddr?
-
Starts the server by listening for connections on the desired
port. This may be re-run to re-start the server.
If no port was specified it defaults to 80. The caller
can specify the qualified host name returned in the Host field of each
server response. This defaults to the result of info hostname.
A non-default interface address can be specified through ipaddr.
Otherwise IP_ADDR_ANY is used so the server can accept
connections from any interface.
Automatically calls Httpd_Init if it has not been
done manually before.
The command returns the empty string.
Note: It is possible for the package to have the server listen
on multiple ports, just call this command more than once. However
note that the package remembers only the last port opened for
listening. This means that a shutdown will stop only connections on
the last port opened with this command, and nothing else.
- Httpd_ServerShutdown
-
This command closes the listening socket of the server. Existing
HTTP connections are kept open, but no new connection will be
possible.
- Httpd_SecureServer ?port? ?name? ?ipaddr?
-
Like Httpd_Server, except that additional setup for SSL is
performed, requiring the package TLS, and that the port
defaults to 443.
- Httpd_SecureServerShutdown
-
Like Httpd_ServerShutdown, except that listening socket
for secure connections is closed.
- Httpd_CurrentSocket ?sock?
-
If a sock is specified it is remembered globally as the current
socket. Otherwise the globally remembered current socket is returned.
- Httpd_Webmaster ?email?
-
Defines a global email address for the webmaster. If no address
was specified the last address set is returned.
- Httpd_VirtualHost host file
-
Initialize a virtual server. The file is an alternate
config file, (e.g., "tclhttpd.rc"). The pages for each
virtual server are processed inside their own safe interpreter.
- Httpd_VirtualHosts hostNames file
-
Like Httpd_VirtualHost except that the first argument
is a list of host names. All of these share the same config file.
- ::Httpd
-
A global array variable containing global configuration information.
- bufsize
-
Chunk size for copies. For example POST data.
- initialized
-
Exists and true after package was initialized by Httpd_Init.
- ipaddr
-
Non-default ipaddr for the server (for multiple interfaces).
- library
-
Path of the directory containing the Tcl scripts.
- port
-
The port this server is serving.
- listen
-
The main listening socket id.
- server
-
The server ID for the HTTP protocol.
- shutdown
-
A list of Tcl callbacks to run when the server shuts down.
- sockblock
-
Blocking mode value for sockets (normally this should be 0).
- timeout1
-
Time before the server closes a kept-alive socket (msecs).
- timeout2
-
Time before the server kills an in-progress transaction (msecs).
- timeout3
-
Time allowed to drain extra post data.
- version
-
The version number.
- maxused
-
Max number of transactions per socket (keep alive).
Management operations for connections.
- ::Httpd$sock
-
The state of the open connection is stored in global variables, one
per connection. These variables are arrays and have the prefix
Httpd. Their distinguishing suffix is the handle of the
channel (socket) they belong to. This means that any user code which
has a connection handle can import the connection state into its
current scope via a command like
The elements of this array are documented here. URL implementations
are free to hang additional state off the data array as long as they
do not clobber the elements documented below. These keys in the state
array are semi-public, or "well known". There are a few API's to
access them, but URL implementations can rely on these:
- self
-
A list of protocol (http or https), name, and port
that capture the server-side of the socket address. Available through
the Httpd_Protocol, Httpd_Name, and Httpd_Port API's.
- uri
-
The complete URL, including protocol, servername, and query.
- proto
-
Either http or https.
- url
-
The URL after the server name and before the '?'. In other words,
the url path.
- query
-
The URL after the '?'.
- ipaddr
-
The remote client's IP address.
- cert
-
Client certificate (The result of tls::status). This is
only relevant to connections coming in over a secure port.
- host
-
The host specified in the URL, if any (proxy case).
- port
-
The port specified in the URL, if any.
- mime,*
-
HTTP header request lines (e.g., mime,content-type).
- count
-
Content-Length.
- set-cookie
-
List of Set-Cookie headers to stick into the response.
Use Httpd_SetCookie to append to this.
- prefix
-
Set by Url_Dispatch (in package httpd::url) to be the
URL domain prefix.
- suffix
-
Set by Url_Dispatch to be the URL domain suffix.
- auth_type
-
Set by the package httpd::auth to "Basic", etc.
- remote_user
-
Set by the package httpd::auth to the
username from Basic authentication.
- session
-
Set by the package httpd::auth to the
"realm,$username" from Basic auth.
You can overwrite this session ID with something more useful.
- Internal
-
Fields used by this module.
- left
-
The number of keep-alive connections allowed.
- cancel
-
AfterID of event that will terminate the connection on timeout.
- state
-
State of request processing.
- version
-
1.0 or 1.1.
- line
-
The current line of the HTTP request.
- mimeorder
-
List indicating the order of MIME header lines.
- key
-
Current header key.
- checkNewLine
-
State bit for Netscape SSL newline bug hack.
- callback
-
Command to invoke when request has completed.
- file_size
-
Size of file returned by Httpd_ReturnFile.
- infile
-
Open file used by fcopy to return a file, or CGI pipe.
- ::env
-
During the dispatch of a request the element HTTP_CHANNEL
contains the channel handle of the connection for that request.
Danger: This is true only until the URL implementation enters
the event loop on its own. After that this element can be overwritten
by another request served in parallel. In other words this information
is not reliable.
A package using this variable is httpd::cookie, especially
the command Cookie_Get.
It would have been better to provide a cookie retrieval command
in this API here.
- Httpd_Port ?sock?
-
If no socket handle sock is provided the regular (non-secure)
listening port is returned. Otherwise the port for the connection
running over the specified socket is returned.
- Httpd_SecurePort
-
Returns the port number of the secure listening port, if a secure
server was activated. An empty string will be returned if no secure
server is running.
- Httpd_Peername sock
-
Returns the DNS name of the client connected to the server over
the socket sock.
- Httpd_Protocol sock
-
Returns the protocol for the connection.
Either http or https.
Used by Httpd_SelfUrl.
- Httpd_Name sock
-
Return the server name for the connection sock.
Used by Httpd_SelfUrl.
- Httpd_SelfUrl url ?sock?
-
This command takes a server-relative url and returns the
equivalent absolute url (containing server name, port, etc). The
connection sock is required to be able to distinguish between
regular and secure ports.
- Httpd_CompletionCallback sock cmd
-
Register a procedure cmd to be called when an HTTP request is
completed on the socket sock, either normally or forcibly
closed. This gives a URL implementation a guaranteed callback to
clean up or log requests.
The callback will be invoked with two additional arguments, sock
and a string, in this order. The string can be empty. If the string is
not empty it will contain an error message.
Note that completed here does not mean completion of getting
all input for the request, but rather that the response to the
request was completed and sent to the client as well.
- Httpd_SockClose sock closeit ?message?
-
"Closes" the connection sock. Note that the socket
channel the connection runs over might actually remain open for a
keep-alive connection. Calling this means a HTTP transaction is fully
complete. The optional message defaults to Close. If the
boolean flag closeit is set the socket for the connection is
closed no matter what type the connection.
This cleans up all state associated with the connection, including
after events for timeouts, the data array, and fileevents.
- Httpd_RequestComplete sock
-
Detect if a request has been sent and completed. The holder of a
socket might need to know if the URL request was completed with one of
the return-data commands, or is still lingering open. The result is a
boolean value. true signals that the last request was fully
completed.
- Httpd_Suspend sock ?timeout?
-
This command, and its counterpart Httpd_Resume can be used by
the backend handling an url to temporarily disable and re-enable the
reception of data from the connection sock. For example if there
are long-lasting server-side operations to handle the request which
block and then enter the event loop on their own.
If a timeout is set for the suspension the pending request will
be forcibly aborted with an error reply when the time runs out.
An example user of this mechanism are the all commands reading posted
data (see below). They suspend normal operation, take over the socket
to read the posted data and when reactivate the normal processing.
- Httpd_Resume sock ?timeout?
-
See Httpd_Suspend above.
- Httpd_Pair sock fd
-
Connects the connection coming in over sock with the channel
fd. Any data arriving on sock is copied over to fd
and vice versa. If either channel is closed the other will be closed
too.
This is the basic mechanism to redirect the internal processing of a
request to an external application, i.e. for CGI processing, or to a
a subordinate web server.
- Httpd_DumpHeaders sock
-
This command returns a dictionary containing the received HTTP
protocol headers for the connection sock. The keys are header
names without the trailing colon and mapped to lower case (e.g.,
content-type). The system adds two pseudo-headers: One that contains
the original request URL; its name is "url". Another that contains the
request protocol; its name is "method". There are no duplications in
the header keys. If any headers were repeated, their values were
combined by separating them with commas.
The commands listed here technically belong to the section
Connection Management, but are important enough to
warrant their own section. They deal with data which was POST'ed as part
of a request (form data, uploaded files).
- Httpd_PostDataSize sock
-
Returns the amount of post data available in bytes for the current
request, i.e. sent over the connection associated with the socket
sock.
- Httpd_GetPostData sock varName ?size?
-
Synchronously reads posted data from the socket sock and appends
it to the buffer variable varName. If size is not
specified Httpd(bufsize) bytes will be read.
The command returns the total number of bytes accumulated so far.
- Httpd_ReadPostDataAsync sock cmd
-
Activates the asynchronous reading of posted data from the socket
sock, as it arrives. Whenever more posted data arrives on the
socket sock the specified command prefix cmd will be
called.
This is a convenience command wrapped around
Httpd_GetPostDataAsync (see below) setting things up so that
arriving data is added to the query component of the status
variable for the connection.
- Httpd_GetPostDataAsync sock varName blockSize cmd
-
Activates the asynchronous reading of posted data from the socket
sock, as it arrives. Whenever more posted data arrives on the
socket sock the data is appended to the specified variable
(varName) and specified command prefix cmd will be called.
The data is read in blocksize chunks.
The specified command prefix cmd is called with three additional
arguments, the sock, the varName, and an additional string,
either empty or containing an error message, in this order.
- Httpd_CopyPostData sock channel cmd
-
An alternative to Httpd_GetPostDataAsync. Sets up the
asynchronous copying of the data posted to the socket sock to
the channel. The command prefix cmd is called when the
copying completed, with two additional argument, sock and
channel, in this order.
- Httpd_GetPostChannel sock sizeName
-
Returns the socket sock containing the posted data, as long as
there is POST data to read for the connection over this socket. If no
data is present (anymore) an error will be thrown. The number of bytes
present is written into the variable sizeName.
The commands listed here technically belong to the section
Connection Management, but are important enough to
warrant their own section. They deal with the generation of replies in
general, predefined and generic. The latter ones can to be used by the
packages implementing the handling of urls
- Httpd_SetCookie sock cookie ?modify?
-
Add the encoded cookie to the reply for the current request on
connection sock. This command has to be called before using
either Httpd_ReturnFile or Httpd_ReturnData.
See http://wp.netscape.com/newsref/std/cookie_spec.html
for the specification of what cookies are and how they work.
See package httpd::cookie for commands to help in
the creation of cookies.
- Httpd_RemoveCookies sock pattern
-
Remove previously set cookies from the reply for the current request
on connection sock. Any cookies that match the glob
pattern are removed. This is useful for expiring a cookie that
was previously set.
- Httpd_ReturnFile sock type path ?offset?
-
Sends the contents of the file with name path and mime type
type as the reply to the current request on the connection
sock. If an offset is specified that number of bytes are
skipped from the start of the file.
The request will be completed by the time this command returns.
This implies that completion callback have been called and that
sock has been closed.
- Httpd_ReturnData sock type content ?code? ?close?
-
Like Httpd_ReturnFile, except that the content is specified
directly as an argument to the command. This command also allows the
specification of an HTTP return code. If none is specified it will
default to 200 (Data follows).
Beyond that the caller can order the command to keep the connection
sock open after the data was sent ("close == 1"). By
default the connection would be closed, like it is done by
Httpd_ReturnFile.
- Httpd_ReturnCacheableData sock type content date ?code?
-
Like Httpd_ReturnData, except that a Last-Modified header is
part of the reply so that proxy servers can cache it. The information
for this header line is taken from date. In contrast to
Httpd_ReturnData the connection is always closed. This is
like for Httpd_ReturnFile.
- Httpd_Error sock code ?detail?
-
Send the error message detail with HTTP response code, log
it, and close the connection sock. This is the most basic error
response the server can generate. Other packages may generate their
own error responses. The package httpd::doc is an example of
this.
- Httpd_Redirect newurl sock
-
This command generates a redirect to newurl reply (code 302) and
then closes the connection sock. It assumes that newurl
contains an absolute url.
- Httpd_RedirectSelf newurl sock
-
A wrapper around Httpd_Redirect for a newurl which is on
this server. In other words, this commands expects a server relative
url, and not an absolute one.
- Httpd_RedirectDir sock
-
Generate a redirect reply for the connection sock because the
trailing slash is not present on a URL that corresponds to a
directory.
- Httpd_NotModified sock
-
This command generates a "Not modified" reply (code 304) and
then closes the connection sock.
- Httpd_RequestAuth sock type realm
-
Generates a "Authorization required" reply (code 401) and then closes
the connection sock. The type is usually basic. The data
in realm is used by browsers to cache credentials.
http::log, httpd::config, httpd::cookie, httpd::counter, httpd::logstd, httpd::threadmgr, httpd::url, httpd::version
http, tclhttpd, web server
Copyright © 2003 Andreas Kupries <andreas_kupries@users.sourceforge.net>


Gracenote images – in the form of cover art, artist images and more – are integral features in many online music services, as well as home, automotive and mobile entertainment devices. Gracenote maintains a comprehensive database of images in dimensions to accommodate all popular applications, including a growing catalog of high-resolution (HD) images.
Gracenote carefully curates images to ensure application and device developers are provided with consistently formatted, high quality images – helping streamline integration and optimize the end-user experience. This topic describes concepts and guidelines for Gracenote images including changes to and support for existing image specifications.
Gracenote provides images in several dimensions to support a variety of applications. Applications or devices must specify image size when requesting an image from Gracenote. All Gracenote images are provided in the JPEG (.jpg) image format.
In general, Gracenote provides images to fit within the following square dimensions.
|
Image Dimension Name |
Pixel Dimensions |
|---|---|
|
75 |
75 x 75 |
|
170 |
170 x 170 |
|
300 |
300 x 300 |
|
450* |
450 x 450 |
|
720* |
720 x 720 |
|
1080* |
1080 x 1080 |
*Images with dimensions 450 x 450 and higher are available online only, or by special request.
Source images are not always square, and may be proportionally resized to fit within the specified square dimensions. Images will always retain their original aspect ratio.
While album cover art is often represented by a square, it is more accurately a bit wider than it is tall. The dimensions of these cover images vary from album to album. Some CD packages, such as a box set, might even be a radically different shape.
Occasionally, an Album result might have missing cover art. If the cover art is missing, Gracenote recommends trying to retrieve the artist image, and if that is not available, trying to retrieve the genre image. If none of these images are available, your application can use a default image as a substitute. Gracenote distributes an clef symbol image to serve as a default replacement. The images are in jpeg format and located in the /images folder of the package. The image names are:
Artist and Contributor images, such as publicity photos, come in a wide range of sizes and both portrait and landscape orientations.
 This allows developers to present images in a fixed area within application or device user interfaces. Gracenote recommends applications center images horizontally and vertically within the predefined square dimensions, and that the square be transparent such that the background shows through. This results in a consistent presentation despite variation in the image dimensions. To ensure optimum image quality for end-users, Gracenote recommends that applications use Gracenote images in their provided pixel dimensions without stretching or resizing.
Gracenote resizes images based on the following guidelines:
Following these guidelines, all resized images will remain as rectangles retaining the same proportions as the original source images. Resized images will fit into squares defined by the available dimensions, but are not themselves necessarily square images.


Double Jeopardy (1999) 2 stars out of 4. Starring Ashley Judd, Tommy Lee Jones and Bruce Greenwood. Directed by Bruce Bereford
"Double Jeopardy" is a straightforward, no-frills, guilty-pleasure movie.

This revenge drama offers no bells or whistles, no twists, turns or surprises.
Everything about it is predictable and preordained.
Basically, what "Double Jeopardy" consists of is a chase. A wife, wrongly imprisoned for killing her husband, is paroled after serving six years, then sets out to find her conniving spouse (who isn't really dead, of course) and her son.
 For example, how did hubby get off the sailboat?  And why wasn't all the blood found on the boat checked to see if it matched that of Nick Parsons (Bruce Greenwood), the husband Libby Parsons (Ashley Judd) was supposed to have killed?
Because if any of that had been accomplished, there would have been no movie.
"Double Jeopardy" is a movie short on details but long on action. After being paroled, Libby immediately breaks parole to begin her quest.
Now searching for her is her parole officer, Travis Lehman (Tommy Lee Jones).
Of course, by film's end, he comes to believe her story of being framed.
Nice scenery and locations, including Washington state and New Orleans, are the main attractions here.
Judd is adequate as the outraged spouse seeking justice, while Jones doesn't seem to be working too hard as Lehman. Actually, he seems to be doing an imitation of his Sam Gerard character from "The Fugitive" and "U.S. Marshals."
Director Bruce Beresford, who helmed the Academy Award-winning "Driving Miss Daisy," is too good a filmmaker to just punch the clock. He keeps "Double Jeopardy" moving, not allowing the audience to think about all the preposterous situations and incongruities that are rife throughout.
"Double Jeopardy" is merely a fun diversion. It's workmanlike and is only there to entertain. If you keep your expectations grounded, you won't be disappointed.
Bob Bloom is the film critic at the Journal and Courier. He can be reached by e-mail at<EMAIL_ADDRESS>or at<EMAIL_ADDRESS>The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).
The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.
Please direct comments/criticisms of the review to relevant newsgroups.
Broken URLs inthe reviews are the responsibility of the author.
The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.
Related links: index of all rec.arts.movies.reviews reviews


Color Spaces
|
Classes | |
| struct | devicen_t< 1 > |
| unnamed color space of one channel More... | |
| struct | devicen_t< 2 > |
| unnamed color space of two channels More... | |
| struct | devicen_t< 3 > |
| unnamed color space of three channels More... | |
| struct | devicen_t< 4 > |
| unnamed color space of four channels More... | |
| struct | devicen_t< 5 > |
| unnamed color space of five channels More... | |
Typedefs | |
|
typedef mpl::vector4< cyan_t, magenta_t, yellow_t, black_t > | cmyk_t |
|
typedef mpl::vector1 < gray_color_t > | gray_t |
|
typedef mpl::vector3< red_t, green_t, blue_t > | rgb_t |
|
typedef mpl::vector4< red_t, green_t, blue_t, alpha_t > | rgba_t |


RAMSADA.io is a landing page site for personal use and learning. Feel free to get in touch with me.
This is created using Jekyll and an awesome theme by Start Bootstrap
Following are some of the projects that I am currently working on


{% extends 'base.html' %} {% block title %} Registration Complete - {{ block.super }} {% endblock title %} {% block content %}
Your account has been registered!


Getting Started
The System Under Test
Because FakeHttp uses a message handler to do its faking, the only requirement for the SUT is that it not instantiate an HttpMessageHandler itself. This is easily accomplished by taking the handler as a parameter, using an IoC containter or via configuration. Whatever mechanism meshes with your design.
So code that looked like this:
public class GeoCoder : IGeoCoder
{
private readonly HttpClient _httpClient;
public GeoCoder()
{
_httpClient = new HttpClient(new HttpClientHandler(), true);
_httpClient.BaseAddress = new Uri("http://dev.virtualearth.net/REST/v1/", UriKind.Absolute);
}
}
Might change to this:
public class GeoCoder : IGeoCoder
{
private readonly HttpClient _httpClient;
public GeoCoder(HttpMessageHandler handler)
{
_httpClient = new HttpClient(handler, false); // flag controls disposal of the handler
_httpClient.BaseAddress = new Uri("http://dev.virtualearth.net/REST/v1/", UriKind.Absolute);
}
}
Getting and Using Fake Responses
The easiest way to set up fake response is to capture them from a live service endpoint. Once captured, they can be stored for future use and/or tweaked to test and simulate how client code behaves with specific response scenarios
FakeHttp implmenets a handful of different message handler types and a factory class that enables a suite of tests to easily switch between them. Assuming you already have, or can write, a suite of tests that interact with a RESTful service the following steps will allow you to fake them. (These examples use MSTest but the same concepts apply to other test frameworks. There is no dependency on MStest)
1. Replace the HttpMessageHandler Used by the Tests
Given a unti test that might look like this, creating the message handler inline:
[TestMethod]
public async Task RoundtripPostalCode()
{
var service = new GeoCoder(new HttpClientHandler(), "api-key");
var coord = await service.GetCoordinate(new Address() { postalCode = "55116", countryRegion = "US" });
var address = await service.GetAddress(coord.Item1, coord.Item2);
Assert.AreEqual("55116", address.postalCode);
}
Change it to:
[TestMethod]
public async Task RoundtripPostalCode()
{
var handler = MessageHandlerFactory.CreateMessageHandler(new FileSystemResources(TestContext.TestRunDirectory));
var service = new GeoCoder(handler, "api-key");
var coord = await service.GetCoordinate(new Address() { postalCode = "55116", countryRegion = "US" });
var address = await service.GetAddress(coord.Item1, coord.Item2);
Assert.AreEqual("55116", address.postalCode);
}
With MSTest, TestContext.TestRunDirectory is a folder wehre deployed items and test results are created for each test run. It is in this folder where the above example will store captured responses.
2. Capture Responses
In order to switch an entire suite of tests from one handler to the next it's easiest to use the MessageHandlerFactory and its MessageHandlerMode. The mode can be switched in a single place where a test run is initialized.
[AssemblyInitialize]
public static void AssemblyInitialize(TestContext context)
{
// set the http message handler factory to the mode we want for the entire assmebly test execution
MessageHandlerFactory.Mode = MessageHandlerMode.Capture;
}
This code tells the factory to create a message handler that will retreive and store the response from any request it processes.
3. Store Responses for Future Use
After running the tests, respsonses and headers will be stored in a folder structure rooted in the TestContext.TestRunDirectory location (this will be in a folder named TestResults in the soltuion directory).
There will be a folder named for each host name captured by the unit tests. Copy each of these folders into the root of your unit test solution diretory or other location for further reference.
Fake data can be made accessible to the unit test in a number of ways:
1) As loose files 2) In a Zip archive 3) As embedded assembly resources
Whichever mechanism is chosen, the directory and file names and structure must be maintained so that FakeHttp can map http requests to faked responses.
4. Run Tests Against Faked Responses
Next we need to wire them into the unit tests and reconfigure FakeHttp to use fakes instead of actual service endpoints.
[AssemblyInitialize]
public static void AssemblyInitialize(TestContext context)
{
// set the http message handler factory to the mode we want for the entire assmebly test execution
MessageHandlerFactory.Mode = MessageHandlerMode.Fake;
}


For safety, this inspection is disabled unless the project uses JDK 5.0.
Powered by InspectionGadgets


Discover the cosmos! Each day a different image or photograph of our fascinating universe is featured, along with a brief explanation written by a professional astronomer.
2019 May 6
Explanation: What would it look like to fly over a spiral galaxy? To help visualize this, astronomers and animators at the Space Telescope Science Institute computed a virtual flyby of the Whirlpool Galaxy (M51) using data and images from the Hubble Space Telescope. At only 25 million light years distant and fully 50 thousand light years across, the Whirlpool is one of the brightest and most picturesque galaxies on the sky. Visible during the virtual flyby are spiral arms dominated by young blue stars, older lighter-colored stars, dark lanes of dust, and bright red emission nebulae. Many galaxies far in the distance can be seen right through M51. The visualization should be considered a time-lapse, because otherwise the speed of the virtual camera would need to be very near the speed of light.
Authors & editors:
Robert Nemiroff
(MTU) &
Jerry Bonnell (UMCP)
NASA Official: Phillip Newman
Specific rights apply.
NASA Web
Privacy Policy and Important Notices
A service of:
ASD at
NASA /
GSFC
& Michigan Tech. U.


Creating Graphs
A graph works by taking a selection of functions from the Browser and sending them to the Graph dialog box. In the Graph dialog box, you construct a function query. If your query contains one or more valid paths between two or more functions, DIScover builds a Graph view or an ASCII report, depending on your choice of output. DIScover informs you that it could not build a graph using the selected functions in the event of missing or incomplete data.
After highlighting a set of functions in the Browser’s Elements or Results columns (one or the other, not both), create a Graph by selecting View > Graph from the main menu. This opens the Graph dialog box with the highlighted entities.
The Graph dialog box lets you take a set of selected functions from the Browser and determine which of the functions serve as source or target in your function query.
Note: The Graph dialog box accepts selected functions from the Elements or Results column, but not from both. If you want to use functions from both columns, select the functions in the Browser, create a group, display the group’s members, and select the desired functions from among the resulting display.
When the Graph dialog box first appears, DIScover places all of the selected functions in the Source column. You need to determine which of these entities you want in the Targets column.
You can use the arrow buttons to move functions between the two columns (Graph allows multiple functions in both columns). This defines your function query for the DIScover path-mapping process.
As with the Browser, you can use keystrokes in the Source and Target columns to:
• find a specific function name (click a column and type the name of a function)
• select all functions (C-/)
• deselect all but the first selected function (C-\)
Related Topics
To add additional functions to the selections in the Graph dialog box


Introducing: NEW CUTTING-EDGE TECHNOLOGY!
What new technologies can help reduce our carbon footprint?
AIR-INK
AIR-INK is a special kind of high-quality ink made from air pollution.
PROS
AIR-INK gets rid of air pollution by repurposing it as ink.
CONS
AIR-INK is dependent on the fact that there is pollution in the air, and so it is very limited.
Edible Water Bottles
This "water bottle" is really just a clear pouch filled with water that humans can digest.
PROS
It is bio-degradable and reduces litter (people would just eat the water bottle once they are done).
CONS
This watter bottle is a choking hazard and should not be given to small children.
LifeStraw
This is a special straw that filters out germs and makes any water directly drinkable.
PROS
This straw could save many lives by giving people drinking water at any time.
CONS
The straw is not totally reliable and you still can get sick if you're not careful.
Drinkable Sea Water (Salt Filter)
This invention filters the salt out of sea water, making it drinkable.
PROS
Ocean water covers 71% of the Earth, so we won't be running out of drinking water anytime soon!
CONS
This specific method kills sea life and is not 100% reliable.


TOGGLE TOOLBAR
Sneha Mohanty
Pencil
Line
Rectangle
Circle
RightTriangle
UpSemiCircle
DownSemiCircle
Pentagon
RandomCircles
Stars
Sketcher
Pixel
GreenLine
Black Fur
Erase Portions
Undo
Save
Fill shape?
Stroke
{{st}}
Fill
{{fl}}
Stroke/Eraser width
{{stw}}
Your browser does not support the canvas element.


How do you turn a collection of XYZ triplets into a surface plot? This is the most frequently asked 3D plotting question that I got when I was in Tech Support.
load seamount who -file seamount
Your variables are: caption x y z
The problem is that the data is made up of individual (x,y,z) measurements. It isn't laid out on a rectilinear grid, which is what the SURF command expects. A simple plot command isn't very useful.
plot3(x,y,z,'.-')
The solution is to use Delaunay triangulation. Let's look at some info about the "tri" variable.
tri = delaunay(x,y);
plot(x,y,'.')


Dutch police find 25 migrants in refrigerated container on U.K.-bound ferry
by The Associated Press, StaffTHE HAGUE, Netherlands - Dutch emergency services gave medical assistance Tuesday night to a group of 25 stowaways found on board a ship that was heading to England.
The stowaways were discovered night in a refrigerated container on board the ship, emergency co-ordination organization Rijnmond Veilig said in a statement.
Two of the stowaways were taken to a hospital for treatment and the remaining 23 were taken to a “police location,” Rijnmond Veilig reported on its website.
It said the ship was heading from the Dutch port of Vlaardingen to Felixstowe in England. Sniffer dogs were being used on the ship to search for any other stowaways.
Dutch broadcaster NOS, citing an unnamed police spokesperson, reported that the ship was a ferry that turned around and headed back to Vlaardingen near Rotterdam after the discovery.
Rijnmond Veilig said that the ship's crew reported that there were no fatalities.
Further details were not immediately available.
The discovery came nearly a month after 39 Vietnamese migrants were found dead in a container truck in the English town of Grays.
The driver of that truck has been charged with 39 counts of manslaughter and conspiracy to traffic people. Police said he drove the cab of the truck to the English port of Purfleet, where it picked up the container, which had arrived by ferry from the port of Zeebrugge in Belgium.