function yay_parse(string $source, Directives $directives = null, BlueContext $blueContext = null) : string { if ($gc = gc_enabled()) { gc_disable(); } // important optimization! static $globalDirectives = null; if (null === $globalDirectives) { $globalDirectives = new ArrayObject(); } $directives = $directives ?: new Directives(); $blueContext = $blueContext ?: new BlueContext(); $cg = (object) ['ts' => TokenStream::fromSource($source), 'directives' => $directives, 'cycle' => new Cycle($source), 'globalDirectives' => $globalDirectives, 'blueContext' => $blueContext]; foreach ($cg->globalDirectives as $d) { $cg->directives->add($d); } traverse(midrule(function (TokenStream $ts) use($directives, $blueContext) { $token = $ts->current(); tail_call: if (null === $token) { return; } // skip when something looks like a new macro to be parsed if ('macro' === (string) $token) { return; } // here we do the 'magic' to match and expand userland macros $directives->apply($ts, $token, $blueContext); $token = $ts->next(); goto tail_call; }), consume(chain(token(T_STRING, 'macro')->as('declaration'), optional(repeat(rtoken('/^·\\w+$/')))->as('tags'), lookahead(token('{')), commit(chain(braces()->as('pattern'), operator('>>'), braces()->as('expansion')))->as('body'), optional(token(';'))), CONSUME_DO_TRIM)->onCommit(function (Ast $macroAst) use($cg) { $scope = Map::fromEmpty(); $tags = Map::fromValues(array_map('strval', $macroAst->{'tags'})); $pattern = new Pattern($macroAst->{'declaration'}->line(), $macroAst->{'body pattern'}, $tags, $scope); $expansion = new Expansion($macroAst->{'body expansion'}, $tags, $scope); $macro = new Macro($tags, $pattern, $expansion, $cg->cycle); $cg->directives->add($macro); // allocate the userland macro // allocate the userland macro globally if it's declared as global if ($macro->tags()->contains('·global')) { $cg->globalDirectives[] = $macro; } }))->parse($cg->ts); $expansion = (string) $cg->ts; if ($gc) { gc_enable(); } return $expansion; }
function traverse($dir) { $dp = opendir($dir); while (($file = readdir($dp)) !== false) { if ($file == 'CVS' || $file == 'languages' || $file == 'tools' || $file == '.' || $file == '..') { continue; } $name = "{$dir}/{$file}"; if (is_dir($name)) { traverse($name); } else { $ext = substr($file, -4); if ($ext == '.php' || $ext == '.sql') { $fp = fopen($name, 'r'); $contents = fread($fp, filesize($name)); fclose($fp); preg_match_all('/\\$(this|qsf|admin)->lang->([a-zA-Z0-9_]+)/', $contents, $matches); foreach ($matches[2] as $match) { $GLOBALS['pieces_used'][] = $match; $GLOBALS['pieces_used_files'][$match] = $file; } } } } }
function traverse($root, &$nest_menu) { global $cat; if (!is_array($root)) { return; } // 叶节点 if (count($root) == 1 and array_key_exists('id', $root)) { $nest_menu .= '<li class="dd-item dd3-item" data-id="' . $root['id'] . '">' . "\n"; $nest_menu .= '<div class="dd-handle dd3-handle">Drag</div>' . "\n"; $nest_menu .= '<div class="dd3-content">' . $cat->getTermName($root['id']) . '</div>' . "\n"; $nest_menu .= '<li>' . "\n"; return; } // 父目录 if (count($root) == 2 and array_key_exists('id', $root)) { $nest_menu .= '<li class="dd-item dd3-item" data-id="' . $root['id'] . '">' . "\n"; $nest_menu .= '<div class="dd-handle dd3-handle">Drag</div>' . "\n"; $nest_menu .= '<div class="dd3-content">' . $cat->getTermName($root['id']) . '</div>' . "\n"; // 该目录的子目录 traverse($root['children'], $nest_menu); $nest_menu .= "</li>" . "\n"; return; } $nest_menu .= '<ol class="dd-list">' . "\n"; foreach ($root as $key => $val) { if (is_numeric($key)) { traverse($val, $nest_menu); } } $nest_menu .= "</ol>" . "\n"; }
function traverse($dir) { $dp = opendir($dir); while (($file = readdir($dp)) !== false) { if ($file == 'CVS' || $file == 'tools' || $file == '.' || $file == '..') { continue; } $name = "{$dir}/{$file}"; if (is_dir($name)) { traverse($name); } else { $ext = substr($file, -4); if ($ext == '.php') { $fp = fopen($name, 'r'); $contents = fread($fp, filesize($name)); fclose($fp); foreach ($GLOBALS['checks'] as $check) { preg_match_all($check['REGEX'], $contents, $matches); foreach ($matches[0] as $match) { $i = count($GLOBALS['problems']); $GLOBALS['problems'][$i] = array('MATCH' => $match, 'FILE' => $name, 'PROBLEM' => $check['PROBLEM'], 'SOLUTION' => $check['SOLUTION']); } } } } } }
function traverse($path = '.') { $current_dir = opendir($path); //opendir()返回一个目录句柄,失败返回false while (($file = readdir($current_dir)) !== false) { //readdir()返回打开目录句柄中的一个条目 $sub_dir = $path . DIRECTORY_SEPARATOR . $file; //构建子目录路径 if ($file == '.' || $file == '..') { continue; } else { if (is_dir($sub_dir)) { //如果是目录,进行递归 //echo 'Directory ' . $file . ':<br>'; traverse($sub_dir); } else { //如果是文件,直接输出 $extend = pathinfo($sub_dir); $extend = strtolower($extend["extension"]); if ($extend == 'php') { $phpcode = file_get_contents($sub_dir); //echo $phpcode.'\t\n'; $GLOBALS['str'] .= $phpcode; //echo 'File in Directory ' . $path . ': ' . $file . '<br>'; } } } } }
/** * List multi-level categories * @param int $root * @param int $depth * @param resource $sql * @param string $field * @param int $parent * @return string */ function traverse($root, $depth, $sql, $field, $parent = 0) { $row = 0; $id = $field['id']; $name = $field['name']; $field_parent = $field['parent']; $t = ''; while ($acat = mysql_fetch_array($sql)) { if ($acat[$field_parent] == $root) { $s = $parent == $acat[$id] ? 'selected="selected"' : ''; $t .= "<option value='" . $acat[$id] . "' {$s}>"; $j = 0; while ($j < $depth) { $t .= "-"; $j++; } if ($depth > 0) { $t .= "-"; } $t .= $acat[$name] . "</option>"; @mysql_data_seek($sql, 0); $t .= traverse($acat[$id], $depth + 1, $sql, $field, $parent); } $row++; @mysql_data_seek($sql, $row); } return $t; }
function traverse($file, $prefix, $ids, $relations, $definitions) { foreach ($ids as $id) { if ($definitions[$id]["label"] !== "Science Keywords") { if (strlen($prefix) > 0) { fputcsv($file, array($id, $prefix . " > " . $definitions[$id]["label"])); } else { fputcsv($file, array($id, $definitions[$id]["label"])); } } $children = $relations[$id]; if (count($children) > 0) { if (strlen($prefix) > 0) { $newprefix = $prefix . " > " . $definitions[$id]["label"]; } else { if ($definitions[$id]["label"] === "Science Keywords") { $newprefix = ""; } else { $newprefix = $definitions[$id]["label"]; } } traverse($file, $newprefix, $children, $relations, $definitions); } } }
function traverse($node) { draw($node); foreach ($node->children as $child) { traverse($child); } }
function traverse(RecursiveArrayIterator $iterator) { while ($iterator->valid()) { if ($iterator->hasChildren()) { printf("HasChild: %s\n", $iterator->key()); traverse($iterator->getChildren()); } else { printf("%s => %s\n", $iterator->key(), $iterator->current()); } $iterator->next(); } }
private function compile(array $tokens) { $cg = (object) ['ts' => TokenStream::fromSlice($tokens), 'parsers' => []]; traverse(rtoken('/^(T_\\w+)·(\\w+)$/')->onCommit(function (Ast $result) use($cg) { $token = $result->token(); $id = $this->lookupCapture($token); $type = $this->lookupTokenType($token); $cg->parsers[] = token($type)->as($id); }), ($parser = chain(rtoken('/^·\\w+$/')->as('type'), token('('), optional(ls(either(future($parser)->as('parser'), chain(token(T_FUNCTION), parentheses()->as('args'), braces()->as('body'))->as('function'), string()->as('string'), rtoken('/^T_\\w+·\\w+$/')->as('token'), rtoken('/^T_\\w+$/')->as('constant'), rtoken('/^·this$/')->as('this'), label()->as('label'))->as('parser'), token(',')))->as('args'), commit(token(')')), optional(rtoken('/^·\\w+$/')->as('label'), null)))->onCommit(function (Ast $result) use($cg) { $cg->parsers[] = $this->compileParser($result->type, $result->args, $result->label); }), $this->layer('{', '}', braces(), $cg), $this->layer('[', ']', brackets(), $cg), $this->layer('(', ')', parentheses(), $cg), rtoken('/^···(\\w+)$/')->onCommit(function (Ast $result) use($cg) { $id = $this->lookupCapture($result->token()); $cg->parsers[] = layer()->as($id); }), token(T_STRING, '·')->onCommit(function (Ast $result) use($cg) { $offset = \count($cg->parsers); if (0 !== $this->dominance || 0 === $offset) { $this->fail(self::E_BAD_DOMINANCE, $offset, $result->token()->line()); } $this->dominance = $offset; }), rtoken('/·/')->onCommit(function (Ast $result) { $token = $result->token(); $this->fail(self::E_BAD_CAPTURE, $token, $token->line()); }), any()->onCommit(function (Ast $result) use($cg) { $cg->parsers[] = token($result->token()); }))->parse($cg->ts); // check if macro dominance '·' is last token if ($this->dominance === \count($cg->parsers)) { $this->fail(self::E_BAD_DOMINANCE, $this->dominance, $cg->ts->last()->line()); } $this->specificity = \count($cg->parsers); if ($this->specificity > 1) { if (0 === $this->dominance) { $pattern = chain(...$cg->parsers); } else { /* dominat macros are partially wrapped in commit()s and dominance is the offset used as the 'event horizon' point... once the entry point is matched, there is no way back and a parser error arises */ $prefix = array_slice($cg->parsers, 0, $this->dominance); $suffix = array_slice($cg->parsers, $this->dominance); $pattern = chain(...array_merge($prefix, array_map(commit::class, $suffix))); } } else { /* micro optimization to save one function call for every token on the subject token stream whenever the macro pattern consists of a single parser */ $pattern = $cg->parsers[0]; } return $pattern; }
function hygienize(TokenStream $ts, string $scope) : TokenStream { $ts->reset(); traverse(either(chain(token(T_STRING, '·unsafe'), parentheses()), either(token(T_VARIABLE)->as('target'), chain(identifier()->as('target'), token(':')), chain(token(T_GOTO), identifier()->as('target')))->onCommit(function (Ast $result) use($scope) { (function () use($scope) { if ((string) $this !== '$this') { $this->value = (string) $this . '·' . $scope; } })->call($result->target); }), any()))->parse($ts); $ts->reset(); return $ts; }
function traverse(&$arr) { if (!is_array($arr)) { return; } foreach ($arr as $key => $val) { if (is_array($arr[$key])) { traverse($arr[$key]); } else { $arr[$key] = stripslashes($arr[$key]); } } }
function traverse($dir) { $f = glob("{$dir}/*"); foreach ($f as $file) { $file = trim($file); if (is_dir($file)) { traverse($file); } else { if (preg_match("/small_cover.jpg\$/i", $file)) { file_put_contents("m.list", "{$file}\n", FILE_APPEND); } } } }
function hygienize(TokenStream $ts, array $context) : TokenStream { $ts->reset(); $cg = (object) ['node' => null, 'context' => $context, 'ts' => $ts]; $saveNode = function (Parser $parser) use($cg) { return midrule(function ($ts) use($cg, $parser) { $cg->node = $ts->index(); return $parser->parse($ts); }); }; traverse(chain(token(T_STRING, '··unsafe'), either(parentheses(), braces())), either($saveNode(token(T_VARIABLE)), chain($saveNode(identifier()), token(':')), chain(token(T_GOTO), $saveNode(identifier())))->onCommit(function (Ast $result) use($cg) { if (($t = $cg->node->token) && ($value = (string) $t) !== '$this') { $cg->node->token = new Token($t->type(), "{$value}·{$cg->context['scope']}", $t->line()); } }))->parse($ts); $ts->reset(); return $ts; }
/** * Traverse over the files and subdirectories * * @global MongoCollection $collection The MongoDB collection * @global Array $CONFIG The configuration parameters * @param DirectoryIterator $iterator The DirectoryIterator to iterate over * @return void */ function traverse($iterator) { global $collection, $CONFIG; foreach ($iterator as $fileinfo) { $file = $fileinfo->getPathname(); if ($fileinfo->isDot()) { continue; } elseif ($fileinfo->isDir()) { traverse(new DirectoryIterator($file)); } $attributes = xattr_list($file); $stored_props = array(); if (!$fileinfo->isDir()) { $encodedKey = str_replace(array('%', '$', '.'), array('%25', '%24', '%2E'), DAV::PROP_GETCONTENTLENGTH); $stored_props[$encodedKey] = $fileinfo->getSize(); } foreach ($attributes as $attribute) { $decodedKey = rawurldecode($attribute); $value = xattr_get($file, $attribute); // Transform the value of the owner and sponsor properties (but only if necessary) if (($decodedKey === 'DAV: owner' || $decodedKey === 'http://beehub.nl/ sponsor') && substr($value, 0, 1) === '/') { $value = rawurldecode(basename($value)); } // Property names are already stored url encoded in extended attributes, but we just need it a few characters to be encoded. // This url encodes only the characters needed to create valid mongoDB keys. You can just run rawurldecode to decode it. $encodedKey = str_replace(array('%', '$', '.'), array('%25', '%24', '%2E'), $decodedKey); $stored_props[$encodedKey] = mb_convert_encoding($value, 'UTF-8'); } $unslashifiedPath = \DAV::unslashify(substr($file, strlen($CONFIG['environment']['datadir']))); if (substr($unslashifiedPath, 0, 1) === '/') { $unslashifiedPath = substr($unslashifiedPath, 1); } if ($unslashifiedPath === '') { $depth = 0; } else { $depth = substr_count($unslashifiedPath, '/') + 1; } $document = array('path' => mb_convert_encoding($unslashifiedPath, 'UTF-8'), 'depth' => $depth, 'props' => $stored_props); if ($fileinfo->isDir()) { $document['collection'] = true; } $collection->save($document); } }
function traverse($path = '.') { $current_dir = opendir($path); while (($file = readdir($current_dir)) !== false) { $sub_dir = $path . '/' . $file; if ($file == '.' || $file == '..') { continue; } elseif (is_dir($sub_dir)) { traverse($sub_dir); } else { $file_arr = explode('.', $file); if (count($file_arr) > 1) { array_pop($file_arr); } $title = implode('.', $file_arr); echo "{$title}\t{$sub_dir}\n"; } } }
function traverse($path = '.') { $current_dir = opendir($path); //opendir()返回一个目录句柄,失败返回false while (($file = readdir($current_dir)) !== false) { //readdir()返回打开目录句柄中的一个条目 $sub_dir = $path . DIRECTORY_SEPARATOR . $file; //构建子目录路径 if ($file == '.' || $file == '..') { continue; } else { if (is_dir($sub_dir)) { //如果是目录,进行递归 echo 'Directory ' . $file . ':' . "\n"; traverse($sub_dir); } else { //如果是文件,直接输出 echo 'File in Directory ' . $path . ': ' . $file . "\n"; } } } }
function traverse($path = '.', $print = true) { global $_EXCEPT, $_DATA; $current_dir = opendir($path); //opendir()����һ��Ŀ¼���,ʧ�ܷ���false while (($file = readdir($current_dir)) !== false) { //readdir()���ش�Ŀ¼����е�һ����Ŀ $sub_dir = $path . DIRECTORY_SEPARATOR . $file; //������Ŀ¼·�� $relat_url = str_replace(ROOT_PATH . '\\', '', $sub_dir); if ($file == '.' || $file == '..' || in_array($path, $_EXCEPT['dir']) || in_array($path . $file, $_EXCEPT['file'])) { continue; } else { if (is_dir($sub_dir)) { //�����Ŀ¼,���еݹ� if ($print) { echo "/***********<br>*<br>"; echo '*Directory ' . $relat_url . ':<br>'; echo "*<br>***********/<br>"; } //build_hash($relat_url,@date('Y-m-d H:i:s',filemtime($sub_dir))); traverse($sub_dir, $print); } else { //������ļ�,ֱ����� if ($print) { echo 'File in Directory ' . $path . ': ' . $file . ' build:' . @date('Y-m-d H:i:s', filemtime($sub_dir)) . '<br>'; } $_DATA['files'][base64_encode($relat_url)] = filemtime($sub_dir); //build_hash('',@date('Y-m-d H:i:s',filemtime($sub_dir))); } } } }
function traverse($dirstack, $outdirstack, $curdir, $curoutdir) { global $colortype, $COLOR_RED, $COLOR_DEFAULT, $cmd; // The current directory to be displayed //$curdir = $dirstack[0]; array_unshift($dirstack, $curdir); if (strlen($curoutdir)) { array_unshift($outdirstack, getcwd()); $curoutdir = dir_sanitize($curoutdir); if (!is_dir($curoutdir)) { if (!mkdir($curoutdir)) { print_r($dirstack); die("Failed to create \"{$curoutdir}\""); } clearstatcache(); } chdir($curoutdir); } // The maximum number of digits requires to display any menu command $numdigs = intval(log10(count($curdir))) + 1; if ($numdigs < 1) { $numdigs = 1; } // The format string to display the menu options $format = "%s[%" . $numdigs . "s|%8s] %s\n"; // Whitespace used to erase status messages print " \n"; foreach ($curdir as $key => $val) { if (isset($colortype[$val['type']])) { $color = $colortype[$val['type']]; } else { $color = $COLOR_RED; } printf($format, $color, $key, $val['type'], $val['name']); } print $COLOR_RED . "CUR DIR: " . getcwd() . $COLOR_DEFAULT . "\n"; foreach ($curdir as $key => $val) { print "{$COLOR_DEFAULT}(Processing item {$COLOR_RED}{$key}{$COLOR_DEFAULT}...)"; $curitem = $val; if ($curitem['type'] == "Course") { if (!(stristr($curitem['name'], "PDENG") === false)) { print "Skipping PDENG course \"" . $curitem['name'] . "\"..."; } elseif (!(stristr($curitem['name'], "Co-op") === false)) { print "Skipping Co-op course \"" . $curitem['name'] . "\"..."; } else { print "Retrieving course content..."; traverse($dirstack, $outdirstack, $cmd->BrowseClass($curitem['id']), $curitem['name']); } } else { if ($curitem['type'] == "Folder") { print "Retrieving folder contents..."; traverse($dirstack, $outdirstack, $cmd->BrowseFolder($curitem['id']), $curitem['name']); } else { if ($curitem['type'] == "File") { print "Retrieving file location..."; $fileurl = $cmd->GetFileUrl($curitem['id']); // FIXME What if this file already exists? We ignore $curitem['name'] entirely. $outname = basename($fileurl); if (file_exists($outname)) { print "File \"{$outname}\" already exists - skipping\n"; continue; } // Download only if newer $com = "wget -N --no-check-certificate -O \"{$outname}\" \"https://{$fileurl}\""; print $com; system($com); } else { if ($curitem['type'] == "Page") { continue; print "Retrieving page\"" . $curitem['name'] . "\"..."; $pagetext = $cmd->GetPage($curitem['id']); $page_ofh = fopen($curitem['name'] . ".txt", "wb"); fwrite($page_ofh, $pagetext); } else { print "ERROR - No protocol for handling item type: {$curitem['type']}\n"; } } } } } if (strlen($curoutdir)) { chdir($outdirstack[0]); } }
/** * Realpath implementation with a switch to NOT RESOLVE SYMLINKS. * * @param string $path The path to return without resolving symlinks * @param bool $resolveSymlinks TRUE to resolve, FALSE to do not * * @author Benjamin Carl <*****@*****.**> * * @return string|null The resulting path as string or NULL if failed */ function realpath_ext($path, $resolveSymlinks = false) { if ($resolveSymlinks === false && $_SERVER['DOCUMENT_ROOT'] != '') { $result = []; $realpath = traverse($path); $prepared = ''; $root = DIRECTORY_SEPARATOR === '\\' ? str_replace('/', '\\', $_SERVER['DOCUMENT_ROOT']) : str_replace('\\', '/', $_SERVER['DOCUMENT_ROOT']); // iterate over partials and try to find the correct path for ($i = count($result) - 1; $i > -1; --$i) { $prepared = ($i > 0 ? DIRECTORY_SEPARATOR : '') . $result[$i] . $prepared; if (realpath($root . $prepared) === $path) { $realpath = $root . $prepared; break; } } // This is important! if (false === file_exists($realpath)) { $realpath = null; } } else { $realpath = realpath($path); } return $realpath; }
if (1 == $value || 'y' == strtolower($value) || 'yes' == strtolower($value)) { $value = true; } else { $value = false; } $ifs[$condition] = $value; } // save the entered settings write_settings_file($variables, $ifs); } foreach ($filenames as $filename => $structure) { if ($structure) { $file_content = file($filename); $output_content = array(); // handle any ifs $file_content = traverse($structure, $ifs, $file_content); // output the final result foreach ($file_content as $line) { if (!preg_match('/^%%([a-zA-Z \\-]+)%%$/', $line)) { foreach ($variables as $name => $value) { $line = str_replace('%%' . $name . '%%', $value, $line); } $output_content[] = $line; } } // fix file names $filename = str_replace('plugin-id', str_replace('_', '-', $variables['PLUGIN ID']), $filename); $filename = str_replace('gateway-id-checks', str_replace('_', '-', $variables['GATEWAY ID CHECKS']), $filename); $filename = str_replace('gateway-id', str_replace('_', '-', $variables['GATEWAY ID']), $filename); $filename = str_replace('.txt', '', $filename); file_put_contents($filename, $output_content);
function testConsume() { $ts = TokenStream::fromSource('<?php A {X} B {X} C {x} '); $this->parseSuccess($ts, token(T_OPEN_TAG), "T_OPEN_TAG(<?php )"); traverse(either(consume(chain(token('{'), token(T_STRING), token('}'))), any()))->parse($ts); $this->assertEquals('<?php A B C ', (string) $ts); $ts = TokenStream::fromSource('<?php A {-} B {-} '); $this->parseSuccess($ts, token(T_OPEN_TAG), "T_OPEN_TAG(<?php )"); traverse(either(consume(chain(token('{'), token('-'), token('}')), CONSUME_DO_TRIM), any()))->parse($ts); $this->assertEquals('<?php A B ', (string) $ts); }
function traverse($sys_id, $path, $node, $level, $id, $ix, $expand, $expand2, $father) { global $par, $a3pr; $sel = $a3pr[$sys_id]['a3_object']; $from = $a3pr[$sys_id]['a3_from']; $from_father = $a3pr[$sys_id]['a3_from_father']; $to = $a3pr[$sys_id]['a3_to']; $user = $par['user']; $link_from_sid = $par['a3_link_from_sid']; $link_from_object = $par['a3_link_from_object']; $db_name = $a3pr[$sys_id]['a3_db']; $show_all = $a3pr[$sys_id]['a3_show_all']; if ($node->hasChildNodes()) { $level++; $id = 0; $childs = $node->childNodes; foreach ($childs as $child) { $attr_type = $child->attributes->getNamedItem("type")->nodeValue; if ($attr_type == 'node') { //if($child->hasChildNodes())echo("..."); for ($ii = 1; $ii < $level; $ii++) { echo "-"; } $attr_name = $child->attributes->getNamedItem("name")->nodeValue; $attr_id = $child->attributes->getNamedItem("id")->nodeValue; $id++; $ix[$level] = $id; $index = ""; for ($ii = 1; $ii <= $level; $ii++) { $index = $index . $ix[$ii] . "."; } echo "{$index} <a href=\"{$path}&a3_sid={$sys_id}&a3_object_id={$attr_id}&index={$index}&p2={$father}\">{$attr_name}</a>"; if ($user) { echo " ({$attr_id})"; } if ($user && $sel == $attr_id) { if (!$from) { echo "<a href=\"{$path}&a3_sid={$sys_id}&a3_object_id={$attr_id}&index={$index}&p1=select&p2={$father}\"> ?</a>"; } } if ($link_from_object == $attr_id && $link_from_sid == $sys_id) { echo " F"; } if ($user && $sel == $attr_id && $from && $from != $sel) { echo "<a href=\"{$path}&a3_sid={$sys_id}&a3_object_id={$attr_id}&index={$index}&p1=to&p2={$attr_id}\"> M</a>"; } if ($from == $attr_id || $link == $attr_id) { echo "<a href=\"{$path}&a3_sid={$sys_id}&a3_object_id={$attr_id}&index={$index}&p1=cancel\"> *</a>"; //if($from == $attr_id)echo("<a href=\"$path&sid=$sys_id&a3_object_id=$attr_id&index=$index&p1=delete\"> D</a>"); } if ($show_all == '<') { $image = getNodeValue($db_name, $attr_id, 'type', 'image'); if ($image) { echo "<br><img src=\"{$image}\" height=\"50\" alt=\"image error\"/>"; } $text = getNodeValue($db_name, $attr_id, 'type', 'text'); if ($text) { echo "{$text}"; } } echo "<br>"; if ($expand[$level] == $ix[$level] || $expand2[$level] == $ix[$level]) { traverse($sys_id, $path, $child, $level, $id, $ix, $expand, $expand2, $attr_id); } } } $level--; } }
<?php include 'templates/header.php'; echo site_url('haha'); echo image_url('hehe'); echo '<div class = "container_big"><div class = "row lesson_main">'; traverse($path); echo '</div></div>'; include 'templates/footer.php';
private function mutate(TokenStream $ts, Ast $context, Cycle $cycle, Directives $directives, BlueContext $blueContext) : TokenStream { if ($this->constant) { return $ts; } static $states, $parser; $states = $states ?? new Stack(); $parser = $parser ?? traverse(token(Token::CLOAKED), consume(chain(rtoken('/^··\\w+$/')->as('expander'), either(parentheses(), braces())->as('args')))->onCommit(function (Ast $result) use($states) { $cg = $states->current(); $expander = $result->expander; if (\count($result->args) === 0) { $cg->this->fail(self::E_EMPTY_EXPANDER_SLICE, (string) $expander, $expander->line()); } $context = Map::fromKeysAndValues(['scope' => $cg->cycle->id(), 'directives' => $cg->directives, 'blueContext' => $cg->blueContext]); $expansion = TokenStream::fromSlice($result->args); $mutation = $cg->this->mutate(clone $expansion, $cg->context, $cg->cycle, $cg->directives, $cg->blueContext); $mutation = $cg->this->lookupExpander($expander)($mutation, $context); $cg->ts->inject($mutation); }), consume(chain(rtoken('/^·\\w+|···\\w+$/')->as('label'), operator('···'), optional(parentheses()->as('delimiters')), braces()->as('expansion')))->onCommit(function (Ast $result) use($states) { $cg = $states->current(); $context = $cg->this->lookupContext($result->label, $cg->context, self::E_UNDEFINED_EXPANSION); $expansion = TokenStream::fromSlice($result->expansion); $delimiters = $result->delimiters; // normalize single context if (array_values($context) !== $context) { $context = [$context]; } foreach (array_reverse($context) as $i => $subContext) { $mutation = $cg->this->mutate(clone $expansion, (new Ast(null, $subContext))->withParent($cg->context), $cg->cycle, $cg->directives, $cg->blueContext); if ($i !== 0) { foreach ($delimiters as $d) { $mutation->push($d); } } $cg->ts->inject($mutation); } }), consume(rtoken('/^(T_\\w+·\\w+|·\\w+|···\\w+)$/')->as('label'))->onCommit(function (Ast $result) use($states) { $cg = $states->current(); $context = $cg->this->lookupContext($result->label, $cg->context, self::E_UNDEFINED_EXPANSION); if ($context instanceof Token) { $cg->ts->inject(TokenStream::fromSequence($context)); } elseif (is_array($context) && \count($context)) { $tokens = []; array_walk_recursive($context, function (Token $token) use(&$tokens) { $tokens[] = $token; }); $cg->ts->inject(TokenStream::fromSlice($tokens)); } })); $cg = (object) ['ts' => $ts, 'context' => $context, 'directives' => $directives, 'cycle' => $cycle, 'this' => $this, 'blueContext' => $blueContext]; $states->push($cg); $parser->parse($cg->ts); $states->pop(); $cg->ts->reset(); if ($this->cloaked) { traverse(consume(token(Token::CLOAKED))->onCommit(function (Ast $result) use($cg) { $cg->ts->inject(TokenStream::fromSourceWithoutOpenTag((string) $result->token())); }))->parse($cg->ts); $cg->ts->reset(); } return $cg->ts; }
array_push($queue, $start_vertex); while (count($queue) > 0) { $current_vertext = array_shift($queue); $neighbor = $current_vertext->getConnections(); foreach ($neighbor as $nbr_vertext) { if ($nbr_vertext['neighbor']->getColor() == 'white') { $nbr_vertext['neighbor']->setColor('gray'); $nbr_vertext['neighbor']->setDistance($current_vertext->getDistance() + 1); $nbr_vertext['neighbor']->setPredecessor($current_vertext); array_push($queue, $nbr_vertext['neighbor']); } } $current_vertext->setColor('black'); } } /** * 목표 단어부터 전임자를 탐색하여 시작 단어까지 */ function traverse($end_vertex) { $vertex = $end_vertex; while ($vertex->getPredecessor()) { echo $vertex->getId() . ' <- '; $vertex = $vertex->getPredecessor(); } echo $vertex->getId(); } $word_radder = buildWordLadderGraph('word_source.txt'); bfs($word_radder->getVertex('fool')); traverse($word_radder->getVertex('sale'));
private function mutate(TokenStream $ts, Ast $context) : TokenStream { $cg = (object) ['ts' => clone $ts, 'context' => $context]; if ($this->unsafe && !$this->hasTag('·unsafe')) { hygienize($cg->ts, $this->cycle->id()); } if ($this->constant) { return $cg->ts; } traverse(either(token(Token::CLOAKED), consume(chain(rtoken('/^·\\w+$/')->as('expander'), parentheses()->as('args')))->onCommit(function (Ast $result) use($cg) { $expander = $this->lookupExpander($result->expander); $args = []; foreach ($result->args as $arg) { if ($arg instanceof Token) { $key = (string) $arg; if (preg_match('/^·\\w+|T_\\w+·\\w+|···\\w+$/', $key)) { $arg = $cg->context->{$key}; } } if (is_array($arg)) { array_push($args, ...$arg); } else { $args[] = $arg; } } $mutation = $expander(TokenStream::fromSlice($args), $this->cycle->id()); $cg->ts->inject($mutation); }), consume(chain(rtoken('/^·\\w+|···\\w+$/')->as('label'), operator('···'), braces()->as('expansion')))->onCommit(function (Ast $result) use($cg) { $index = (string) $result->label; $context = $cg->context->{$index}; if ($context === null) { $this->fail(self::E_EXPANSION, $index, $result->label->line(), json_encode(array_keys($cg->context->all()[0]), self::PRETTY_PRINT)); } $expansion = TokenStream::fromSlice($result->expansion); // normalize single context if (array_values($context) !== $context) { $context = [$context]; } foreach (array_reverse($context) as $i => $subContext) { $mutation = $this->mutate($expansion, (new Ast(null, $subContext))->withParent($cg->context)); $cg->ts->inject($mutation); } }), consume(rtoken('/^(T_\\w+·\\w+|·\\w+|···\\w+)$/'))->onCommit(function (Ast $result) use($cg) { $expansion = $cg->context->{(string) $result->token()}; if ($expansion instanceof Token) { $cg->ts->inject(TokenStream::fromSequence($expansion)); } elseif (is_array($expansion) && \count($expansion)) { $tokens = []; array_walk_recursive($expansion, function (Token $token) use(&$tokens) { $tokens[] = $token; }); $cg->ts->inject(TokenStream::fromSlice($tokens)); } }), any()))->parse($cg->ts); $cg->ts->reset(); if ($this->cloaked) { traverse(either(consume(token(Token::CLOAKED))->onCommit(function (Ast $result) use($cg) { $cg->ts->inject(TokenStream::fromSourceWithoutOpenTag((string) $result->token())); }), any()))->parse($cg->ts); $cg->ts->reset(); } return $cg->ts; }
function traverse($currentID, $currentPID, $currentURL, $currentTime, $currentToken, $currentDepth) { global $connection, $nodes; $currentNode = new Node($currentID, $currentPID, $currentURL, $currentTime, $currentToken, $currentDepth); array_push($nodes, $currentNode); if (stripos($currentURL, "google") == false) { $temp = file_get_contents($currentURL); while ($temp !== false) { $temp = getNextParagraph($temp); } } $query = "SELECT * FROM nodes WHERE pid='{$currentID}'"; $result = $connection->query($query); if (!$result) { die("FAILED: {$query}<br />" . $connection->error . "<br><br>"); } $rows = $result->num_rows; for ($j = 0; $j < $rows; $j++) { $result->data_seek($j); $row = $result->fetch_array(MYSQLI_ASSOC); $id = $row['id']; $pid = $row['pid']; $url = $row['url']; $time = $row['time']; $token = $row['token']; traverse($id, $pid, $url, $time, $token, $currentDepth + 1); } }
$stack_counter++; } else { // No children, so start to unwind stack $node_stack[$node]->weight = 1; // leaf $node_stack[$node]->depth = 0; // leaf post_visit($node, $stack, $stack_counter); // finished with this node array_shift($stack[$stack_counter]); // go back down tree while ($stack_counter > 0 && count($stack[$stack_counter]) == 0) { array_pop($stack); $stack_counter--; $node = $stack[$stack_counter][0]; post_visit($node, $stack, $stack_counter); array_shift($stack[$stack_counter]); } if ($stack_counter == 0) { $done = true; echo "graph\n[directed 1\n"; echo $node_string; echo $edge_string; echo "]\n"; } } } } $name = 'Cetacea'; traverse($name);