/** * Applies a function to items of the array and concatenates the results. * This is also known as `flatMap` in some libraries. * ```php * $words = chain(split(' ')); * $words(['Hello World', 'How are you']) // ['Hello', 'World', 'How', 'are', 'you'] * ``` * * @signature (a -> [b]) -> [a] -> [b] * @param callable $fn * @param array $list * @return array */ function chain() { $chain = function ($fn, $list) { return concatAll(map($fn, $list)); }; return apply(curry($chain), func_get_args()); }
/** * Memoizes callbacks and returns there value instead of calling them * * @param callable $callback Callable closure or function * @param array $arguments Arguments * @param array|string $key Optional memoize key to override the auto calculated hash * @return mixed */ function memoize($callback, array $arguments = array(), $key = null) { Exceptions\InvalidArgumentException::assertCallback($callback, __FUNCTION__, 1); static $keyGenerator = null, $storage = array(); if (!$keyGenerator) { $keyGenerator = function ($value) use(&$keyGenerator) { $type = gettype($value); if ($type === 'array') { $key = join(':', map($value, $keyGenerator)); } elseif ($type === 'object') { $key = get_class($value) . ':' . spl_object_hash($value); } else { $key = (string) $value; } return $key; }; } if ($key === null) { $key = $keyGenerator(array_merge(array($callback), $arguments)); } else { $key = $keyGenerator($key); } if (!isset($storage[$key]) && !array_key_exists($key, $storage)) { $storage[$key] = call_user_func_array($callback, $arguments); } return $storage[$key]; }
/** * Generates a table with a header column and a value column from the given array. * * @param mixed $value * @param string $title [optional] * @param int $maxDepth [optional] Max. recursion depth. * @param array $excludeProps [optional] Exclude properties whose name is on the list. * @param bool $excludeEmpty [optional] Exclude empty properties. * @param int $depth [optional] For internal use. * @return string */ public static function grid($value, $title = '', $maxDepth = 1, $excludeProps = [], $excludeEmpty = false, $depth = 0) { if (is_null($value) || is_scalar($value)) { return self::toString($value); } if ($depth >= $maxDepth) { return "<i>(...)</i>"; } if (is_object($value)) { if (method_exists($value, '__debugInfo')) { $value = $value->__debugInfo(); } else { $value = get_object_vars($value); } } if ($title) { $title = "<p><b>{$title}</b></p>"; } // Exclude some properties ($excludeProps) from $value. $value = array_diff_key($value, array_fill_keys($excludeProps, false)); if ($excludeEmpty) { $value = array_prune_empty($value); } return $value ? "{$title}<table class=__console-table><colgroup><col width=160><col width=100%></colgroup>\n" . implode('', map($value, function ($v, $k) use($depth, $maxDepth, $excludeProps, $excludeEmpty) { $v = self::grid($v, '', $maxDepth, $excludeProps, $excludeEmpty, $depth + 1); return "<tr><th>{$k}<td>{$v}"; })) . "\n</table>" : '<i>[]</i>'; }
function map($nav, $item = 0, $object) { if (!empty($nav[$item])) { ?> <ul> <?php foreach ($nav[$item] as $key => $value) { ?> <li> <a href="<?php echo $object->url(explode('/', $value['location'])); ?> "> <?php echo $value['name']; ?> </a> <?php map($nav, $key, $object); ?> </li> <?php } ?> </ul> <?php } }
function solution($list) { $acc = 1; $func = function ($item, $acc) { return $acc * $item; }; $cellItAll = map($list, function ($item) { //map return ceil($item); }); $leaveJustEven = filter($cellItAll, function ($item) { //filter return $item % 2 == 0; }); $multiplyKill = accumulate($leaveJustEven, $func, $acc); //reduce ###################################################### // one line solution // return accumulate(filter(map($list, function($item) { // return ceil($item); // }), function($item) { // return $item % 2 == 0; // }), function($item, $acc) { // return $acc * $item; // }, $acc); return $multiplyKill; }
function rop_findexec() { $x = []; $p = ptr() + 0; for ($i = 0; $i < 0x2000; $i++) { array_push($x, [0x41414141, 0x41414141, 0x41414141, 0x41414141, 0x41414141, 0x41414141, 0x41414141, 0x41414141, 0x41414141, 0x41414141, 0x41414141, 0x41414141]); } $a = map($p, 0x10000)[0]; nogc($a); $a = bin2hex($a); nogc($a); $r = strpos($a, "3100000000000000100000000f0000000c000000010000000c00000000000000"); if ($r !== FALSE) { $a = substr($a, $r + 0x80, 0x10); $a = hexdec(swapEndianness($a)); $a = $a + 0; for ($i = 0; $i < 0x100000; $i++) { $k = map(($a & ~0xff) - 0x100 * $i, 0x8); if ("cffaedfe07000001" == bin2hex($k[0])) { return ($a & ~0xff) - 0x100 * $i + 0; } } } return FALSE; }
function map($fn, $list, $new_list = array()) { if (!car($list)) { return $new_list; } $new_list[] = $fn(car($list)); return map($fn, cdr($list), $new_list); }
function test_map() { $a = function ($x) { return $x * $x; }; $range = range(0, 10); return is_identical(map($a, $range), array_map($a, $range)); }
public function testMap() { $expectedArr = array(2, 4, 6); $result = map(array(1, 2, 3), function ($item) { return $item * 2; }); $this->assertEquals($result, $expectedArr); }
public function testMap() { $range = range(0, 5); $mapped = map(function ($n) { return $n * 3; }, $range); $this->assertSame([0, 3, 6, 9, 12, 15], toArray($mapped)); }
/** @test */ public function shouldCancelInputArrayPromises() { $mock1 = $this->getMockBuilder('React\\Promise\\CancellablePromiseInterface')->getMock(); $mock1->expects($this->once())->method('cancel'); $mock2 = $this->getMockBuilder('React\\Promise\\CancellablePromiseInterface')->getMock(); $mock2->expects($this->once())->method('cancel'); map([$mock1, $mock2], $this->mapper())->cancel(); }
/** * Returns a list resulting in invoking a function with each element of a list. * * @param callable $proc a function to invoke * @param Cons $alist a list */ function map($proc, $alist) { if (isNull($alist)) { return nil(); } elseif (isPair($alist)) { return cons($proc(car($alist)), map($proc, cdr($alist))); } else { throw new \InvalidArgumentException("{$alist} is not a proper list"); } }
function __debugInfo() { $linkToUrl = function (NavigationLinkInterface $link) { return $link->rawUrl(); }; return ['Current link' => $this->currentLink(), 'All IDs<sup>*</sup>' => PA($this->IDs)->keys()->sort()->join(', ')->S, 'All URLs<sup>*</sup><br>' . '<i>(in scanning order)</i>' => map($this->rootLink->getDescendants(), function (NavigationLinkInterface $link, &$i) { $i = $link->rawUrl(); return $link->url(); }), 'Trail<sup>*</sup>' => map($this->getCurrentTrail(), $linkToUrl), 'Visible trail<sup>*</sup>' => map($this->getVisibleTrail(), $linkToUrl), 'Navigation map<sup>*</sup>' => iterator_to_array($this->rootLink), 'request' => $this->request()]; }
function test_basic() { $function = function ($value) { return $value * 2; }; $input = [1, 2, 3]; $expect = [2, 4, 6]; $map = map($function); $actual = iterator_to_array($map($input)); $this->assertEquals($expect, $actual); }
function getAll() { $names = $this->getPropertyNames(); // We must expose the 'macro' property on this method only, so that that macros can be correctly unserialized $names[] = 'macro'; $x = map($names, function ($v, &$k) { $k = $v; return $this->{$k}; }); return $x; }
function run($times, $length) { $a = new Benchmark('Functional Map x' . $times); $a1 = new Benchmark('Functional Map(w\\o plus) my_map x' . $times); $a2 = new Benchmark('Functional Map(w\\o plus) array_map x' . $times); $b = new Benchmark('array_map x' . $times); $c = new Benchmark('nromal map x' . $times); $manager = new Manager(); $manager->addBenchmarks([$a, $a1, $a2, $b, $c]); $data = []; for ($i = 0; $i < $length; $i++) { $data[] = $i * 2 + 1; } $a->start(); $plus = plus(1); for ($i = 0; $i < $times; $i++) { $res = map($plus, $data); } $a->stop(); $a1->start(); for ($i = 0; $i < $times; $i++) { $res = map2(function ($x) { return $x + 1; }, $data); } $a1->stop(); $a2->start(); for ($i = 0; $i < $times; $i++) { $res = map(function ($x) { return $x + 1; }, $data); } $a2->stop(); $b->start(); $func = function ($x) { return $x + 1; }; for ($i = 0; $i < $times; $i++) { $res = array_map($func, $data); } $b->stop(); $c->start(); $func = function ($x) { return $x + 1; }; for ($i = 0; $i < $times; $i++) { $res = []; foreach ($data as $i) { $res[] = $func($i); } } $c->stop(); echo $manager->getResults('Test Array len =' . $length); }
function get_mitglied($id) { $arr = ''; $query = "SELECT *,IF (DATE_FORMAT( CURDATE( ), '%m%d' ) >= DATE_FORMAT( geburtstag , '%m%d' ) , DATE_FORMAT( CURDATE( ) , '%Y' ) - DATE_FORMAT(geburtstag, '%Y' ) , DATE_FORMAT( CURDATE( ) , '%Y' ) - DATE_FORMAT( geburtstag, '%Y' ) -1) AS alter_jahre FROM mitglieder LEFT JOIN status ON (status.id=mitglieder.status) LEFT JOIN beitraghv ON (beitraghv.id=mitglieder.beitraghv) LEFT JOIN beitragst ON (beitragst.id=mitglieder.beitragst) LEFT JOIN beitragt ON (beitragt.id=mitglieder.beitragt) WHERE mid = {$id}"; $result = mysql_query($query) or die('Query failed: ' . mysql_error()); while ($line = mysql_fetch_assoc($result)) { foreach ($line as $key => $col_value) { if (map("mitglieder", $key)) { $arr[map("mitglieder", $key)] = utf8_encode($col_value); } } } return $arr; }
function __call($name, $args) { $method = "filter_{$name}"; if (isset($this->filters[$method])) { return call_user_func_array($this->filters[$method], $args); } if (isset($this->fallbackHandler)) { if (method_exists($this->fallbackHandler, $method)) { return call_user_func_array([$this->fallbackHandler, $method], $args); } } throw new FilterHandlerNotFoundException(sprintf("<p><p>Handler method: <kbd>%s</kbd><p>Arguments: <kbd>%s</kbd>", $method, print_r(map($args, function ($e) { return Debug::typeInfoOf($e); }), true))); }
function getQueries() { $this->mute(); $queries = map($this->db->connection()->pretend(function () { $this->run(); }), function (array $info) { $bindings = $info['bindings']; return preg_replace_callback('/\\?/', function () use(&$bindings) { $v = current($bindings); next($bindings); return $this->quote($v); }, $info['query']); }); $this->mute(false); return $queries; }
/** * 本体実行前にクラスを初期化する。 */ static function init() { //GET、POST、COOKIEの初期化 self::$post = $_POST; self::$get = $_GET; self::$cookie = $_COOKIE; if (get_magic_quotes_gpc()) { self::$post = map('stripslashes', self::$post); self::$get = map('stripslashes', self::$get); self::$cookie = map('stripslashes', self::$cookie); } self::$get = map('rawurldecode', self::$get); if (ini_get('mbstring.encoding_translation')) { $encode = ini_get('mbstring.internal_encoding'); $proc = "return mb_convert_encoding(\$str, 'UTF-8', '{$encode}');"; self::$post = map(create_function('$str', $proc), self::$post); } }
public function model() { $myRole = $this->session->user()->roleField(); if ($myRole < UserInterface::USER_ROLE_ADMIN) { // Can't view other users. throw new HttpException(403); } $class = $this->userModel; $users = $class::orderBy('username')->get(); //TODO: order by custom username column $users = filter($users, function (UserInterface $user) use($myRole) { return $user->roleField() <= $myRole; }); $users = map($users, function (UserInterface $user) { return $user->getRecord(); }); $this->modelController->setModel($users); }
public function __construct($filename, $mode = 'read', array $paths = null) { switch ($mode) { case 'read': $m = "was not found"; break; case 'write': $m = "can't be written to"; break; case 'delete': $m = "can't be deleted"; break; default: throw new \RuntimeException("Invalid mode {$mode}."); } $extra = $paths ? sprintf("<p>The file was searched for at:<ul>%s</ul>", implode('', map($paths, function ($p) use($filename) { return "<li><pre>{$p}/{$filename}</pre>"; }))) : ''; parent::__construct("File '<kbd>{$filename}</kbd>' {$m}.{$extra}"); }
public function send(EmailMessage $message, $data = []) { $recipient = function (Email $email) { return $email->getValue(); }; $commaSeparated = curry('implode', ', '); $formatRecipients = compose($commaSeparated, map($recipient)); $recipientsString = $formatRecipients($message->recipients); // Append the original recipients to the end of the email for debug purposes $message->body .= <<<EOT ------------- DEBUG INFO ---------------- Original recipients: {$recipientsString} ---------------------------------------------- EOT; // Alter the recipients to send them all to the dev mailbox $message->recipients = [$this->destinationEmail]; // Send the email using the normal mailer $this->mailer->send($message, $data); }
/** * Loads CSV-formatted data from a stream, parses it and returns an array of arrays. * * It closes the stream before returning. * Data should be comma-delimited and string may be enclosed on double quotes. * * @param resource $handle An opened stream. * @param array|string|null $columns Either:<ul> * <li> an array of column names, * <li> a string of comma-delimited (and possibly quoted) column names, * <li> null (or ommited) to read column names from the first row of data. * </ul> * @param string $delimiter The character used for separating fields. If not specified, it will be * auto-decteded, if possible. If it's not possible, a comma will be used. * @return array The loaded data. */ static function loadCsvFromStream($handle, $columns = null, $delimiter = '') { if (is_null($columns)) { $columns = removeBOM(fgets($handle)); } if (is_string($columns)) { if (!$delimiter) { $delimiter = self::autoDetectSeparator($columns); } $columns = map(explode($delimiter, $columns), function ($col) { return preg_replace("/^[\\s\"\t']|[\\s\"\t']\$/", '', $col); }); } else { if (!$delimiter) { $delimiter = ','; } } // use fgetcsv which tends to work better than str_getcsv in some cases $data = []; $i = 0; $row = ''; try { while ($row = fgetcsv($handle, null, $delimiter, '"')) { ++$i; $data[] = array_combine($columns, $row); } fclose($handle); } catch (ErrorException $e) { echo "\nInvalid row #{$i}\n\nColumns:\n"; var_export($columns); echo "\n\nRow:\n"; var_export($row); echo "\n"; exit(1); } return $data; }
/** * レコードをすべて取得する。 * * @param Resource $result クエリの結果セット。 * @return array(array(mixed)) */ public function fetchall($result) { $ret = $result->fetchAll(); if (get_magic_quotes_runtime()) { return map('stripslashes', $ret); } return $ret; }
<?php echo @map_api(array()); ?> <div class="row"> <div class="span12"> <?php echo @helper('ui.header'); ?> </div> </div> <div class="an-entity"> <div class="entity-meta"> <?php echo @map($location); ?> </div> <h2 class="entity-title"> <?php echo @escape($location->name); ?> </h2> <div class="entity-meta"> <?php echo @helper('address', $location); ?> </div>
function image_to_hough($image) { $x_size = imagesx($image); // height $y_size = imagesy($image); // width $r_max = sqrt($x_size * $x_size + $y_size * $y_size); ///2); //echo "width $x_size height $y_size"; // get hough transform $output = array(); for ($y = 0; $y < $y_size; $y++) { for ($x = 0; $x < $x_size; $x++) { $colors = imagecolorsforindex($image, imagecolorat($image, $x, $y)); $color_val = round(($colors['red'] + $colors['green'] + $colors['blue']) / 3); // get average value of image $threshold = 128; // or whatever if ($color_val > $threshold) { // if pixel is above threshold #echo "$x $y pixel value $color_val is above threshold<br>"; // map x and y to the range of -1 to 1 $x_m = map($x, 0, $x_size, -1, 1); //w $y_m = map($y, 0, $y_size, -1, 1); //h // for every angle get the radius and mark // the point in the parameter space // $theta is angle #for($theta = 0.0; $theta < pi(); $theta += pi() / $y_size) {//increment in radians for ($t = 0; $t < $x_size; $t++) { $theta = $t / $x_size * pi(); $r = ($x - $x_size / 2.0) * cos($theta) + ($y - $y_size / 2.0) * sin($theta); // rho #$r = (($x - ($x_size / 2.0)) * cos($theta)) + (($y - ($y_size / 2.0)) * sin($theta)); // rho $r = -($r - $r_max); $r = ($r - $r_max / 2.0) * 2; if (!($r < 0) && !($r > $r_max * 2)) { $x_h = floor(map($theta, 0, pi(), 0, $x_size - 1)); $y_h = floor(map($r, 0, $r_max * 2, 0, $y_size - 1)); $increment = 1; if (isset($output[$x_h][$y_h])) { if ($output[$x_h][$y_h] < 256 - $increment) { $output[$x_h][$y_h] += $increment; } } else { $output[$x_h][$y_h] = $increment; } } //if } //for } //if } //for x loop } //for y loop $output_image = imagecreatetruecolor($x_size, $y_size); foreach ($output as $x => $y_array) { foreach ($y_array as $y => $color) { $color = imagecolorallocate($output_image, $color, 0, 0); imagesetpixel($output_image, $x + 1, $y + 1, $color); } // foreach } // foreach return $output_image; }
echo map($path_wifi_wifi1 . "/nwkey/wep/size", "", "64"); ?> </WEPKeyBits> <SupportedWEPKeyBits> <int>64</int> <int>128</int> </SupportedWEPKeyBits> <Key><?php echo $key; ?> </Key> <RadiusIP1><?php echo query($path_wifi_wifi1 . "/nwkey/eap/radius"); ?> </RadiusIP1> <RadiusPort1><?php echo map($path_wifi_wifi1 . "/nwkey/eap/port", "", "0"); ?> </RadiusPort1> <RadiusIP2><?php echo query($path_wifi_wifi1 . "/nwkey/eap/radius"); ?> </RadiusIP2> <RadiusPort2><?php echo map($path_wifi_wifi1 . "/nwkey/eap/port", "", "0"); ?> </RadiusPort2> </GetWLanSecurityResponse> </soap:Body> </soap:Envelope>
<?php $_ginfo["page"] = curfilename(); $_ginfo["query"] = array(); $formconv = array("dob" => array(function ($inp, $add = array()) { mergeifunset($add, array('format' => null)); if (isset($inp["dob"])) { $inp["dob"] = Fun::timetostr_t3($inp["dob"], $add["format"]); } return $inp; }, function ($inp, $add = array()) { mergeifunset($add, array('format' => null)); if (isset($inp["dob"])) { $inp["dob"] = Fun::strtotime_t3($inp["dob"], $add["format"]); } return $inp; }), "name" => array(function ($inp, $add = array()) { if (isset($inp["name"])) { $msvar = explode(" ", $inp["name"] . " ", 2); mergeifunset($inp, map(array("fname", "lname"), f('$msvar[$ind]'), array("isindexed" => true))); } return $inp; }, function ($inp) { if (isallset(array("fname", "lname"), $inp)) { $inp["name"] = $inp["fname"] . " " . $inp["lname"]; } return $inp; }));
print $id; ?> "> </FORM> <!-- END UNIT VIEW --> <?php if (!my_is_float($lat)) { map("v", get_variable('def_lat'), get_variable('def_lng'), FALSE); // default center, no icon } else { if ($lat == 0.999999 && $lng == 0.999999) { // checks for facilities input in no maps mode 7/28/10 map("v", get_variable('def_lat'), get_variable('def_lng'), FALSE); // default center, no icon } else { map("v", $lat, $lng, TRUE); // do icon } } ?> <!-- 1408 --> <A NAME="bottom" /> <DIV ID='to_top' style="position:fixed; bottom:50px; left:50px; height: 12px; width: 10px;" onclick = "location.href = '#top';"><IMG SRC="markers/up.png" BORDER=0></div> </BODY> </HTML> <?php exit; } // end if ($_GET['view']) // ============================================= initial display ======================= $do_list_and_map = TRUE;