repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
list
docstring
stringlengths
3
47.2k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
91
247
partition
stringclasses
1 value
oat-sa/lib-generis-search
src/AbstractQuerySerialyser.php
AbstractQuerySerialyser.getOperator
protected function getOperator($operator) { /** * @todo change that for a factory */ if(array_key_exists($operator, $this->supportedOperators)) { $operatorClass = $this->operatorNameSpace . '\\' . ($this->supportedOperators[$operator]); $operator = $this->getServiceLocator()->get($operatorClass); $operator->setDriverEscaper($this->getDriverEscaper()); return $operator; } throw new QueryParsingException('this driver doesn\'t support ' . $operator . ' operator'); }
php
protected function getOperator($operator) { /** * @todo change that for a factory */ if(array_key_exists($operator, $this->supportedOperators)) { $operatorClass = $this->operatorNameSpace . '\\' . ($this->supportedOperators[$operator]); $operator = $this->getServiceLocator()->get($operatorClass); $operator->setDriverEscaper($this->getDriverEscaper()); return $operator; } throw new QueryParsingException('this driver doesn\'t support ' . $operator . ' operator'); }
[ "protected", "function", "getOperator", "(", "$", "operator", ")", "{", "/**\n * @todo change that for a factory\n */", "if", "(", "array_key_exists", "(", "$", "operator", ",", "$", "this", "->", "supportedOperators", ")", ")", "{", "$", "operatorCl...
operator command factory @param type $operator @return \oat\search\base\command\OperatorConverterInterface @throws QueryParsingException
[ "operator", "command", "factory" ]
bf19991d7fb807341f7889f7e786f09668013a13
https://github.com/oat-sa/lib-generis-search/blob/bf19991d7fb807341f7889f7e786f09668013a13/src/AbstractQuerySerialyser.php#L211-L223
train
oat-sa/lib-generis-search
src/AbstractQuerySerialyser.php
AbstractQuerySerialyser.setNextSeparator
protected function setNextSeparator($and) { if(!is_null($this->nextSeparator)) { $this->addSeparator($this->nextSeparator); } $this->nextSeparator = $and; return $this; }
php
protected function setNextSeparator($and) { if(!is_null($this->nextSeparator)) { $this->addSeparator($this->nextSeparator); } $this->nextSeparator = $and; return $this; }
[ "protected", "function", "setNextSeparator", "(", "$", "and", ")", "{", "if", "(", "!", "is_null", "(", "$", "this", "->", "nextSeparator", ")", ")", "{", "$", "this", "->", "addSeparator", "(", "$", "this", "->", "nextSeparator", ")", ";", "}", "$", ...
change next separator to "and" or "or" @param boolean $and @return $this
[ "change", "next", "separator", "to", "and", "or", "or" ]
bf19991d7fb807341f7889f7e786f09668013a13
https://github.com/oat-sa/lib-generis-search/blob/bf19991d7fb807341f7889f7e786f09668013a13/src/AbstractQuerySerialyser.php#L230-L237
train
oat-sa/lib-generis-search
src/DbSql/TaoRdf/UnionQuerySerialyser.php
UnionQuerySerialyser.mergeCondition
protected function mergeCondition(&$command, $condition, $separator = null) { $command .= (is_null($separator)) ? '' : ' ' . $this->getDriverEscaper()->dbCommand($separator); $command .= ' ' . $condition . $this->operationSeparator; return $this; }
php
protected function mergeCondition(&$command, $condition, $separator = null) { $command .= (is_null($separator)) ? '' : ' ' . $this->getDriverEscaper()->dbCommand($separator); $command .= ' ' . $condition . $this->operationSeparator; return $this; }
[ "protected", "function", "mergeCondition", "(", "&", "$", "command", ",", "$", "condition", ",", "$", "separator", "=", "null", ")", "{", "$", "command", ".=", "(", "is_null", "(", "$", "separator", ")", ")", "?", "''", ":", "' '", ".", "$", "this", ...
merge multiple condition QueryCriterion @param string $command @param string $condition @param string $separator @return $this
[ "merge", "multiple", "condition", "QueryCriterion" ]
bf19991d7fb807341f7889f7e786f09668013a13
https://github.com/oat-sa/lib-generis-search/blob/bf19991d7fb807341f7889f7e786f09668013a13/src/DbSql/TaoRdf/UnionQuerySerialyser.php#L199-L205
train
oat-sa/lib-generis-search
src/DbSql/TaoRdf/UnionQuerySerialyser.php
UnionQuerySerialyser.sortedQueryPrefix
protected function sortedQueryPrefix(array $aliases) { $sortFields = []; $result = $this->getDriverEscaper()->dbCommand('SELECT') . ' ' . $this->getDriverEscaper()->reserved('subject') . ' ' . $this->getDriverEscaper()->dbCommand('FROM') . $this->operationSeparator . '(' . $this->getDriverEscaper()->dbCommand('SELECT') . ' ' . $this->getDriverEscaper()->reserved('mainq') . '.' . $this->getDriverEscaper()->reserved('subject') . $this->getDriverEscaper()->getFieldsSeparator(); foreach ($aliases as $alias) { $sortFields[] = $this->getDriverEscaper()->reserved($alias['name']) . '.' . $this->getDriverEscaper()->reserved('object') . ' ' . $this->getDriverEscaper()->dbCommand('AS') . ' ' . $alias['name']; } $result .= implode($this->getDriverEscaper()->getFieldsSeparator(), $sortFields) . ' ' . $this->getDriverEscaper()->dbCommand('FROM') . ' ' . ' ( ' . $this->query . ' ) AS mainq ' . $this->operationSeparator; return $result; }
php
protected function sortedQueryPrefix(array $aliases) { $sortFields = []; $result = $this->getDriverEscaper()->dbCommand('SELECT') . ' ' . $this->getDriverEscaper()->reserved('subject') . ' ' . $this->getDriverEscaper()->dbCommand('FROM') . $this->operationSeparator . '(' . $this->getDriverEscaper()->dbCommand('SELECT') . ' ' . $this->getDriverEscaper()->reserved('mainq') . '.' . $this->getDriverEscaper()->reserved('subject') . $this->getDriverEscaper()->getFieldsSeparator(); foreach ($aliases as $alias) { $sortFields[] = $this->getDriverEscaper()->reserved($alias['name']) . '.' . $this->getDriverEscaper()->reserved('object') . ' ' . $this->getDriverEscaper()->dbCommand('AS') . ' ' . $alias['name']; } $result .= implode($this->getDriverEscaper()->getFieldsSeparator(), $sortFields) . ' ' . $this->getDriverEscaper()->dbCommand('FROM') . ' ' . ' ( ' . $this->query . ' ) AS mainq ' . $this->operationSeparator; return $result; }
[ "protected", "function", "sortedQueryPrefix", "(", "array", "$", "aliases", ")", "{", "$", "sortFields", "=", "[", "]", ";", "$", "result", "=", "$", "this", "->", "getDriverEscaper", "(", ")", "->", "dbCommand", "(", "'SELECT'", ")", ".", "' '", ".", ...
add prefix if query is sorted @param array $aliases @return string
[ "add", "prefix", "if", "query", "is", "sorted" ]
bf19991d7fb807341f7889f7e786f09668013a13
https://github.com/oat-sa/lib-generis-search/blob/bf19991d7fb807341f7889f7e786f09668013a13/src/DbSql/TaoRdf/UnionQuerySerialyser.php#L251-L277
train
oat-sa/lib-generis-search
src/DbSql/TaoRdf/UnionQuerySerialyser.php
UnionQuerySerialyser.orderByPart
protected function orderByPart(array $aliases) { $sortFields = []; foreach ($aliases as $alias) { $sortFields[] = $this->getDriverEscaper()->reserved($alias['name']) . '.' . $this->getDriverEscaper()->reserved('object') . ' ' . $alias['dir'] . $this->operationSeparator; } $result = $this->getDriverEscaper()->dbCommand('ORDER BY') . ' ' . implode($this->getDriverEscaper()->getFieldsSeparator(), $sortFields) . $this->operationSeparator; return $result; }
php
protected function orderByPart(array $aliases) { $sortFields = []; foreach ($aliases as $alias) { $sortFields[] = $this->getDriverEscaper()->reserved($alias['name']) . '.' . $this->getDriverEscaper()->reserved('object') . ' ' . $alias['dir'] . $this->operationSeparator; } $result = $this->getDriverEscaper()->dbCommand('ORDER BY') . ' ' . implode($this->getDriverEscaper()->getFieldsSeparator(), $sortFields) . $this->operationSeparator; return $result; }
[ "protected", "function", "orderByPart", "(", "array", "$", "aliases", ")", "{", "$", "sortFields", "=", "[", "]", ";", "foreach", "(", "$", "aliases", "as", "$", "alias", ")", "{", "$", "sortFields", "[", "]", "=", "$", "this", "->", "getDriverEscaper"...
return Order by string @param array $aliases @return string
[ "return", "Order", "by", "string" ]
bf19991d7fb807341f7889f7e786f09668013a13
https://github.com/oat-sa/lib-generis-search/blob/bf19991d7fb807341f7889f7e786f09668013a13/src/DbSql/TaoRdf/UnionQuerySerialyser.php#L284-L298
train
oat-sa/lib-generis-search
src/DbSql/TaoRdf/UnionQuerySerialyser.php
UnionQuerySerialyser.addRandomSort
protected function addRandomSort() { $random = ''; $this->query .= $this->operationSeparator . $this->getDriverEscaper()->dbCommand('ORDER BY') . ' ' . $this->getDriverEscaper()->random() . $this->operationSeparator; return $random; }
php
protected function addRandomSort() { $random = ''; $this->query .= $this->operationSeparator . $this->getDriverEscaper()->dbCommand('ORDER BY') . ' ' . $this->getDriverEscaper()->random() . $this->operationSeparator; return $random; }
[ "protected", "function", "addRandomSort", "(", ")", "{", "$", "random", "=", "''", ";", "$", "this", "->", "query", ".=", "$", "this", "->", "operationSeparator", ".", "$", "this", "->", "getDriverEscaper", "(", ")", "->", "dbCommand", "(", "'ORDER BY'", ...
set sort as random @return string
[ "set", "sort", "as", "random" ]
bf19991d7fb807341f7889f7e786f09668013a13
https://github.com/oat-sa/lib-generis-search/blob/bf19991d7fb807341f7889f7e786f09668013a13/src/DbSql/TaoRdf/UnionQuerySerialyser.php#L365-L374
train
oat-sa/lib-generis-search
src/QueryBuilder.php
QueryBuilder.newQuery
public function newQuery() { $factory = $this->factory; $factory->setServiceLocator($this->serviceLocator); return $factory->get($this->queryClassName)->setParent($this); }
php
public function newQuery() { $factory = $this->factory; $factory->setServiceLocator($this->serviceLocator); return $factory->get($this->queryClassName)->setParent($this); }
[ "public", "function", "newQuery", "(", ")", "{", "$", "factory", "=", "$", "this", "->", "factory", ";", "$", "factory", "->", "setServiceLocator", "(", "$", "this", "->", "serviceLocator", ")", ";", "return", "$", "factory", "->", "get", "(", "$", "th...
generate a new query @return \oat\search\base\QueryInterface
[ "generate", "a", "new", "query" ]
bf19991d7fb807341f7889f7e786f09668013a13
https://github.com/oat-sa/lib-generis-search/blob/bf19991d7fb807341f7889f7e786f09668013a13/src/QueryBuilder.php#L80-L84
train
oat-sa/lib-generis-search
src/DbSql/TaoRdf/Command/In.php
In.setValuesList
protected function setValuesList(array $values) { $parseValues = []; foreach ($values as $value) { $parseValues[] = $this->getDriverEscaper()->quote($this->getDriverEscaper()->escape($value)); } return '(' . implode(' ' . $this->getDriverEscaper()->getFieldsSeparator() . ' ' , $parseValues) . ')'; }
php
protected function setValuesList(array $values) { $parseValues = []; foreach ($values as $value) { $parseValues[] = $this->getDriverEscaper()->quote($this->getDriverEscaper()->escape($value)); } return '(' . implode(' ' . $this->getDriverEscaper()->getFieldsSeparator() . ' ' , $parseValues) . ')'; }
[ "protected", "function", "setValuesList", "(", "array", "$", "values", ")", "{", "$", "parseValues", "=", "[", "]", ";", "foreach", "(", "$", "values", "as", "$", "value", ")", "{", "$", "parseValues", "[", "]", "=", "$", "this", "->", "getDriverEscape...
create condition for object @param array $values @return string
[ "create", "condition", "for", "object" ]
bf19991d7fb807341f7889f7e786f09668013a13
https://github.com/oat-sa/lib-generis-search/blob/bf19991d7fb807341f7889f7e786f09668013a13/src/DbSql/TaoRdf/Command/In.php#L46-L52
train
oat-sa/lib-generis-search
src/factory/FactoryAbstract.php
FactoryAbstract.isValidClass
protected function isValidClass($object) { if(is_a($object, $this->validInterface)) { return true; } throw new \InvalidArgumentException(get_class($object) . ' doesn\'t implements ' . $this->validInterface ); }
php
protected function isValidClass($object) { if(is_a($object, $this->validInterface)) { return true; } throw new \InvalidArgumentException(get_class($object) . ' doesn\'t implements ' . $this->validInterface ); }
[ "protected", "function", "isValidClass", "(", "$", "object", ")", "{", "if", "(", "is_a", "(", "$", "object", ",", "$", "this", "->", "validInterface", ")", ")", "{", "return", "true", ";", "}", "throw", "new", "\\", "InvalidArgumentException", "(", "get...
verify if class implements valid interface @param Object $object @throws \InvalidArgumentException @return boolean
[ "verify", "if", "class", "implements", "valid", "interface" ]
bf19991d7fb807341f7889f7e786f09668013a13
https://github.com/oat-sa/lib-generis-search/blob/bf19991d7fb807341f7889f7e786f09668013a13/src/factory/FactoryAbstract.php#L47-L53
train
oat-sa/lib-generis-search
src/Command/OperatorAbstractfactory.php
OperatorAbstractfactory.canCreateServiceWithName
public function canCreateServiceWithName(ServiceLocatorInterface $serviceLocator, $name, $requestedName) { $interface = 'oat\search\base\command\OperatorConverterInterface'; return (class_exists($requestedName) && in_array($interface , class_implements($requestedName))); }
php
public function canCreateServiceWithName(ServiceLocatorInterface $serviceLocator, $name, $requestedName) { $interface = 'oat\search\base\command\OperatorConverterInterface'; return (class_exists($requestedName) && in_array($interface , class_implements($requestedName))); }
[ "public", "function", "canCreateServiceWithName", "(", "ServiceLocatorInterface", "$", "serviceLocator", ",", "$", "name", ",", "$", "requestedName", ")", "{", "$", "interface", "=", "'oat\\search\\base\\command\\OperatorConverterInterface'", ";", "return", "(", "class_ex...
verify if class name is an existing operator @param ServiceLocatorInterface $serviceLocator @param type $name @param type $requestedName @return boolean
[ "verify", "if", "class", "name", "is", "an", "existing", "operator" ]
bf19991d7fb807341f7889f7e786f09668013a13
https://github.com/oat-sa/lib-generis-search/blob/bf19991d7fb807341f7889f7e786f09668013a13/src/Command/OperatorAbstractfactory.php#L51-L54
train
oat-sa/lib-generis-search
src/DbSql/TaoRdf/QuerySerialyser.php
QuerySerialyser.setLanguageCondition
public function setLanguageCondition($language , $emptyAvailable = false) { $languageField = $this->getDriverEscaper()->reserved('l_language'); $languageValue = $this->getDriverEscaper()->escape($language); $sql = '('; $sql .= $languageField .' = ' . $this->getDriverEscaper()->quote($languageValue) . ''; if($emptyAvailable) { $sql .= ' ' . $this->getDriverEscaper()->dbCommand('OR') . ' ' . $languageField . ' = ' . $this->getDriverEscaper()->getEmpty(); } $sql .= ') ' . $this->getDriverEscaper()->dbCommand('AND') . $this->operationSeparator; return $sql; }
php
public function setLanguageCondition($language , $emptyAvailable = false) { $languageField = $this->getDriverEscaper()->reserved('l_language'); $languageValue = $this->getDriverEscaper()->escape($language); $sql = '('; $sql .= $languageField .' = ' . $this->getDriverEscaper()->quote($languageValue) . ''; if($emptyAvailable) { $sql .= ' ' . $this->getDriverEscaper()->dbCommand('OR') . ' ' . $languageField . ' = ' . $this->getDriverEscaper()->getEmpty(); } $sql .= ') ' . $this->getDriverEscaper()->dbCommand('AND') . $this->operationSeparator; return $sql; }
[ "public", "function", "setLanguageCondition", "(", "$", "language", ",", "$", "emptyAvailable", "=", "false", ")", "{", "$", "languageField", "=", "$", "this", "->", "getDriverEscaper", "(", ")", "->", "reserved", "(", "'l_language'", ")", ";", "$", "languag...
return an SQL string with language filter condition @param string $language @param boolean $emptyAvailable @return string
[ "return", "an", "SQL", "string", "with", "language", "filter", "condition" ]
bf19991d7fb807341f7889f7e786f09668013a13
https://github.com/oat-sa/lib-generis-search/blob/bf19991d7fb807341f7889f7e786f09668013a13/src/DbSql/TaoRdf/QuerySerialyser.php#L134-L144
train
oat-sa/lib-generis-search
src/factory/QueryFactory.php
QueryFactory.get
public function get($className , array $options = array()) { $Query = $this->getServiceLocator()->get($className); if($this->isValidClass($Query)) { return $Query->setServiceLocator($this->getServiceLocator())->setOptions($options); } }
php
public function get($className , array $options = array()) { $Query = $this->getServiceLocator()->get($className); if($this->isValidClass($Query)) { return $Query->setServiceLocator($this->getServiceLocator())->setOptions($options); } }
[ "public", "function", "get", "(", "$", "className", ",", "array", "$", "options", "=", "array", "(", ")", ")", "{", "$", "Query", "=", "$", "this", "->", "getServiceLocator", "(", ")", "->", "get", "(", "$", "className", ")", ";", "if", "(", "$", ...
return a new Query @param string $className @param array $options @return \oat\search\factory\QueryInterface @throws \InvalidArgumentException
[ "return", "a", "new", "Query" ]
bf19991d7fb807341f7889f7e786f09668013a13
https://github.com/oat-sa/lib-generis-search/blob/bf19991d7fb807341f7889f7e786f09668013a13/src/factory/QueryFactory.php#L45-L51
train
oat-sa/lib-generis-search
src/AbstractSearchGateWay.php
AbstractSearchGateWay.init
public function init() { $options = $this->getServiceLocator()->get('search.options'); $this->setOptions($options); $this->driverName = $options['driver']; $this->setDriverEscaper($this->getServiceLocator()->get($this->driverList[$this->driverName])); return $this; }
php
public function init() { $options = $this->getServiceLocator()->get('search.options'); $this->setOptions($options); $this->driverName = $options['driver']; $this->setDriverEscaper($this->getServiceLocator()->get($this->driverList[$this->driverName])); return $this; }
[ "public", "function", "init", "(", ")", "{", "$", "options", "=", "$", "this", "->", "getServiceLocator", "(", ")", "->", "get", "(", "'search.options'", ")", ";", "$", "this", "->", "setOptions", "(", "$", "options", ")", ";", "$", "this", "->", "dr...
init the gateway @return $this
[ "init", "the", "gateway" ]
bf19991d7fb807341f7889f7e786f09668013a13
https://github.com/oat-sa/lib-generis-search/blob/bf19991d7fb807341f7889f7e786f09668013a13/src/AbstractSearchGateWay.php#L87-L94
train
oat-sa/lib-generis-search
src/AbstractSearchGateWay.php
AbstractSearchGateWay.serialyse
public function serialyse(QueryBuilderInterface $Builder) { $this->parsedQuery = $this->getSerialyser()->setCriteriaList($Builder)->serialyse(); return $this; }
php
public function serialyse(QueryBuilderInterface $Builder) { $this->parsedQuery = $this->getSerialyser()->setCriteriaList($Builder)->serialyse(); return $this; }
[ "public", "function", "serialyse", "(", "QueryBuilderInterface", "$", "Builder", ")", "{", "$", "this", "->", "parsedQuery", "=", "$", "this", "->", "getSerialyser", "(", ")", "->", "setCriteriaList", "(", "$", "Builder", ")", "->", "serialyse", "(", ")", ...
parse QueryBuilder and store parsed query @param QueryBuilderInterface $Builder @return $this
[ "parse", "QueryBuilder", "and", "store", "parsed", "query" ]
bf19991d7fb807341f7889f7e786f09668013a13
https://github.com/oat-sa/lib-generis-search/blob/bf19991d7fb807341f7889f7e786f09668013a13/src/AbstractSearchGateWay.php#L101-L104
train
oat-sa/lib-generis-search
src/AbstractSearchGateWay.php
AbstractSearchGateWay.getSerialyser
public function getSerialyser() { $serialyser = $this->getServiceLocator()->get($this->serialyserList[$this->driverName]); $serialyser->setServiceLocator($this->serviceLocator)->setDriverEscaper($this->driverEscaper)->setOptions($this->options)->prefixQuery(); return $serialyser; }
php
public function getSerialyser() { $serialyser = $this->getServiceLocator()->get($this->serialyserList[$this->driverName]); $serialyser->setServiceLocator($this->serviceLocator)->setDriverEscaper($this->driverEscaper)->setOptions($this->options)->prefixQuery(); return $serialyser; }
[ "public", "function", "getSerialyser", "(", ")", "{", "$", "serialyser", "=", "$", "this", "->", "getServiceLocator", "(", ")", "->", "get", "(", "$", "this", "->", "serialyserList", "[", "$", "this", "->", "driverName", "]", ")", ";", "$", "serialyser",...
query serialyser factory @return QuerySerialyserInterface
[ "query", "serialyser", "factory" ]
bf19991d7fb807341f7889f7e786f09668013a13
https://github.com/oat-sa/lib-generis-search/blob/bf19991d7fb807341f7889f7e786f09668013a13/src/AbstractSearchGateWay.php#L135-L139
train
oat-sa/lib-generis-search
src/AbstractSearchGateWay.php
AbstractSearchGateWay.query
public function query() { $builder = $this->getServiceLocator()->get($this->builderClassName); $builder->setOptions($this->options)->setServiceLocator($this->serviceLocator); return $builder; }
php
public function query() { $builder = $this->getServiceLocator()->get($this->builderClassName); $builder->setOptions($this->options)->setServiceLocator($this->serviceLocator); return $builder; }
[ "public", "function", "query", "(", ")", "{", "$", "builder", "=", "$", "this", "->", "getServiceLocator", "(", ")", "->", "get", "(", "$", "this", "->", "builderClassName", ")", ";", "$", "builder", "->", "setOptions", "(", "$", "this", "->", "options...
query builder factory @return QueryBuilder
[ "query", "builder", "factory" ]
bf19991d7fb807341f7889f7e786f09668013a13
https://github.com/oat-sa/lib-generis-search/blob/bf19991d7fb807341f7889f7e786f09668013a13/src/AbstractSearchGateWay.php#L163-L167
train
apfelbox/PHP-File-Download
src/FileDownload.php
FileDownload.sendDownload
public function sendDownload ($filename, $forceDownload = true) { if (headers_sent()) { throw new \RuntimeException("Cannot send file to the browser, since the headers were already sent."); } header("Pragma: public"); header("Expires: 0"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Cache-Control: private", false); header("Content-Type: {$this->getMimeType($filename)}"); if ($forceDownload) { header("Content-Disposition: attachment; filename=\"{$filename}\";" ); } else { header("Content-Disposition: filename=\"{$filename}\";" ); } header("Content-Transfer-Encoding: binary"); header("Content-Length: {$this->getFileSize()}"); @ob_clean(); rewind($this->filePointer); fpassthru($this->filePointer); }
php
public function sendDownload ($filename, $forceDownload = true) { if (headers_sent()) { throw new \RuntimeException("Cannot send file to the browser, since the headers were already sent."); } header("Pragma: public"); header("Expires: 0"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Cache-Control: private", false); header("Content-Type: {$this->getMimeType($filename)}"); if ($forceDownload) { header("Content-Disposition: attachment; filename=\"{$filename}\";" ); } else { header("Content-Disposition: filename=\"{$filename}\";" ); } header("Content-Transfer-Encoding: binary"); header("Content-Length: {$this->getFileSize()}"); @ob_clean(); rewind($this->filePointer); fpassthru($this->filePointer); }
[ "public", "function", "sendDownload", "(", "$", "filename", ",", "$", "forceDownload", "=", "true", ")", "{", "if", "(", "headers_sent", "(", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "\"Cannot send file to the browser, since the headers were alr...
Sends the download to the browser @param string $filename @param bool $forceDownload @throws \RuntimeException is thrown, if the headers are already sent
[ "Sends", "the", "download", "to", "the", "browser" ]
ac97f04d89fe8a9ad9de811162953db3f07685b1
https://github.com/apfelbox/PHP-File-Download/blob/ac97f04d89fe8a9ad9de811162953db3f07685b1/src/FileDownload.php#L55-L84
train
apfelbox/PHP-File-Download
src/FileDownload.php
FileDownload.getMimeType
private function getMimeType ($fileName) { $fileExtension = pathinfo($fileName, PATHINFO_EXTENSION); $mimeTypeHelper = Mimetypes::getInstance(); $mimeType = $mimeTypeHelper->fromExtension($fileExtension); return !is_null($mimeType) ? $mimeType : "application/force-download"; }
php
private function getMimeType ($fileName) { $fileExtension = pathinfo($fileName, PATHINFO_EXTENSION); $mimeTypeHelper = Mimetypes::getInstance(); $mimeType = $mimeTypeHelper->fromExtension($fileExtension); return !is_null($mimeType) ? $mimeType : "application/force-download"; }
[ "private", "function", "getMimeType", "(", "$", "fileName", ")", "{", "$", "fileExtension", "=", "pathinfo", "(", "$", "fileName", ",", "PATHINFO_EXTENSION", ")", ";", "$", "mimeTypeHelper", "=", "Mimetypes", "::", "getInstance", "(", ")", ";", "$", "mimeTyp...
Returns the mime type of a file name @param string $fileName @return string
[ "Returns", "the", "mime", "type", "of", "a", "file", "name" ]
ac97f04d89fe8a9ad9de811162953db3f07685b1
https://github.com/apfelbox/PHP-File-Download/blob/ac97f04d89fe8a9ad9de811162953db3f07685b1/src/FileDownload.php#L95-L102
train
apfelbox/PHP-File-Download
src/FileDownload.php
FileDownload.createFromFilePath
public static function createFromFilePath ($filePath) { if (!is_file($filePath)) { throw new \InvalidArgumentException("File does not exist"); } else if (!is_readable($filePath)) { throw new \InvalidArgumentException("File to download is not readable."); } return new FileDownload(fopen($filePath, "rb")); }
php
public static function createFromFilePath ($filePath) { if (!is_file($filePath)) { throw new \InvalidArgumentException("File does not exist"); } else if (!is_readable($filePath)) { throw new \InvalidArgumentException("File to download is not readable."); } return new FileDownload(fopen($filePath, "rb")); }
[ "public", "static", "function", "createFromFilePath", "(", "$", "filePath", ")", "{", "if", "(", "!", "is_file", "(", "$", "filePath", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "\"File does not exist\"", ")", ";", "}", "else", "if...
Creates a new file download from a file path @static @param string $filePath @throws \InvalidArgumentException is thrown, if the given file does not exist or is not readable @return FileDownload
[ "Creates", "a", "new", "file", "download", "from", "a", "file", "path" ]
ac97f04d89fe8a9ad9de811162953db3f07685b1
https://github.com/apfelbox/PHP-File-Download/blob/ac97f04d89fe8a9ad9de811162953db3f07685b1/src/FileDownload.php#L130-L142
train
goto-bus-stop/recanalyst
src/Analyzers/PlayerMetaAnalyzer.php
PlayerMetaAnalyzer.readPlayerMeta
protected function readPlayerMeta($i) { $player = new Player($this->rec); $player->number = $i; $player->index = $this->readHeader('l', 4); $human = $this->readHeader('l', 4); $length = $this->readHeader('L', 4); if ($length) { $player->name = $this->readHeaderRaw($length); } else { $player->name = ''; } $player->humanRaw = $human; $player->human = $human === 0x02; $player->spectator = $human === 0x06; return $player; }
php
protected function readPlayerMeta($i) { $player = new Player($this->rec); $player->number = $i; $player->index = $this->readHeader('l', 4); $human = $this->readHeader('l', 4); $length = $this->readHeader('L', 4); if ($length) { $player->name = $this->readHeaderRaw($length); } else { $player->name = ''; } $player->humanRaw = $human; $player->human = $human === 0x02; $player->spectator = $human === 0x06; return $player; }
[ "protected", "function", "readPlayerMeta", "(", "$", "i", ")", "{", "$", "player", "=", "new", "Player", "(", "$", "this", "->", "rec", ")", ";", "$", "player", "->", "number", "=", "$", "i", ";", "$", "player", "->", "index", "=", "$", "this", "...
Reads a player meta info block for a single player. This just includes their nickname, index and "human" status. More information about players is stored later on in the recorded game file and is read by the PlayerInfoBlockAnalyzer. Player meta structure: int32 index; int32 human; // indicates whether player is AI/human/spectator uint32 nameLength; char name[nameLength]; @return \RecAnalyst\Model\Player
[ "Reads", "a", "player", "meta", "info", "block", "for", "a", "single", "player", ".", "This", "just", "includes", "their", "nickname", "index", "and", "human", "status", ".", "More", "information", "about", "players", "is", "stored", "later", "on", "in", "...
daec4916d04a73cf89f9325ad77bfaf0644fda06
https://github.com/goto-bus-stop/recanalyst/blob/daec4916d04a73cf89f9325ad77bfaf0644fda06/src/Analyzers/PlayerMetaAnalyzer.php#L61-L77
train
goto-bus-stop/recanalyst
src/Analyzers/PlayerMetaAnalyzer.php
PlayerMetaAnalyzer.seek
private function seek() { $version = $this->get(VersionAnalyzer::class); $constant2 = pack('c*', 0x9A, 0x99, 0x99, 0x99, 0x99, 0x99, 0xF9, 0x3F); $separator = pack('c*', 0x9D, 0xFF, 0xFF, 0xFF); $playersByIndex = []; $size = strlen($this->header); $this->position = 0; $triggerInfoPos = strrpos($this->header, $constant2, $this->position) + strlen($constant2); $gameSettingsPos = strrpos($this->header, $separator, -($size - $triggerInfoPos)) + strlen($separator); $this->position = $gameSettingsPos + 8; if (!$version->isAoK) { // Skip Map ID. $this->position += 4; } // Skip difficulty & diplomacy lock. $this->position += 8; // TODO Is 12.3 the correct cutoff point? if ($version->subVersion >= 12.3) { // TODO what are theeeese? $this->position += 16; } }
php
private function seek() { $version = $this->get(VersionAnalyzer::class); $constant2 = pack('c*', 0x9A, 0x99, 0x99, 0x99, 0x99, 0x99, 0xF9, 0x3F); $separator = pack('c*', 0x9D, 0xFF, 0xFF, 0xFF); $playersByIndex = []; $size = strlen($this->header); $this->position = 0; $triggerInfoPos = strrpos($this->header, $constant2, $this->position) + strlen($constant2); $gameSettingsPos = strrpos($this->header, $separator, -($size - $triggerInfoPos)) + strlen($separator); $this->position = $gameSettingsPos + 8; if (!$version->isAoK) { // Skip Map ID. $this->position += 4; } // Skip difficulty & diplomacy lock. $this->position += 8; // TODO Is 12.3 the correct cutoff point? if ($version->subVersion >= 12.3) { // TODO what are theeeese? $this->position += 16; } }
[ "private", "function", "seek", "(", ")", "{", "$", "version", "=", "$", "this", "->", "get", "(", "VersionAnalyzer", "::", "class", ")", ";", "$", "constant2", "=", "pack", "(", "'c*'", ",", "0x9A", ",", "0x99", ",", "0x99", ",", "0x99", ",", "0x99...
Find the position of the small player metadata block.
[ "Find", "the", "position", "of", "the", "small", "player", "metadata", "block", "." ]
daec4916d04a73cf89f9325ad77bfaf0644fda06
https://github.com/goto-bus-stop/recanalyst/blob/daec4916d04a73cf89f9325ad77bfaf0644fda06/src/Analyzers/PlayerMetaAnalyzer.php#L82-L110
train
goto-bus-stop/recanalyst
src/Model/Team.php
Team.addPlayer
public function addPlayer(Player $player) { $this->players[] = $player; if ($this->index == -1) { $this->index = $player->team; } }
php
public function addPlayer(Player $player) { $this->players[] = $player; if ($this->index == -1) { $this->index = $player->team; } }
[ "public", "function", "addPlayer", "(", "Player", "$", "player", ")", "{", "$", "this", "->", "players", "[", "]", "=", "$", "player", ";", "if", "(", "$", "this", "->", "index", "==", "-", "1", ")", "{", "$", "this", "->", "index", "=", "$", "...
Adds a player to the team. @param \RecAnalyst\Model\Player $player The player we wish to add @return void
[ "Adds", "a", "player", "to", "the", "team", "." ]
daec4916d04a73cf89f9325ad77bfaf0644fda06
https://github.com/goto-bus-stop/recanalyst/blob/daec4916d04a73cf89f9325ad77bfaf0644fda06/src/Model/Team.php#L30-L36
train
goto-bus-stop/recanalyst
src/ResourcePacks/AgeOfEmpires/Civilization.php
Civilization.isAoKCiv
public static function isAoKCiv($id) { return in_array($id, [ self::BRITONS, self::FRANKS, self::GOTHS, self::TEUTONS, self::JAPANESE, self::CHINESE, self::BYZANTINES, self::PERSIANS, self::SARACENS, self::TURKS, self::VIKINGS, self::MONGOLS, self::CELTS, ]); }
php
public static function isAoKCiv($id) { return in_array($id, [ self::BRITONS, self::FRANKS, self::GOTHS, self::TEUTONS, self::JAPANESE, self::CHINESE, self::BYZANTINES, self::PERSIANS, self::SARACENS, self::TURKS, self::VIKINGS, self::MONGOLS, self::CELTS, ]); }
[ "public", "static", "function", "isAoKCiv", "(", "$", "id", ")", "{", "return", "in_array", "(", "$", "id", ",", "[", "self", "::", "BRITONS", ",", "self", "::", "FRANKS", ",", "self", "::", "GOTHS", ",", "self", "::", "TEUTONS", ",", "self", "::", ...
Checks if a civilization is included in the Age of Kings base game. @param int $id Civilization ID. @return bool True if the given civilization exists in AoK, false otherwise.
[ "Checks", "if", "a", "civilization", "is", "included", "in", "the", "Age", "of", "Kings", "base", "game", "." ]
daec4916d04a73cf89f9325ad77bfaf0644fda06
https://github.com/goto-bus-stop/recanalyst/blob/daec4916d04a73cf89f9325ad77bfaf0644fda06/src/ResourcePacks/AgeOfEmpires/Civilization.php#L84-L101
train
goto-bus-stop/recanalyst
src/ResourcePacks/AgeOfEmpires/Civilization.php
Civilization.isAoCCiv
public static function isAoCCiv($id) { return in_array($id, [ self::SPANISH, self::AZTECS, self::MAYANS, self::HUNS, self::KOREANS, ]); }
php
public static function isAoCCiv($id) { return in_array($id, [ self::SPANISH, self::AZTECS, self::MAYANS, self::HUNS, self::KOREANS, ]); }
[ "public", "static", "function", "isAoCCiv", "(", "$", "id", ")", "{", "return", "in_array", "(", "$", "id", ",", "[", "self", "::", "SPANISH", ",", "self", "::", "AZTECS", ",", "self", "::", "MAYANS", ",", "self", "::", "HUNS", ",", "self", "::", "...
Checks if a civilization was added in the Age of Conquerors expansion. @param int $id Civilization ID. @return bool True if the given civilization is part of AoC, false otherwise.
[ "Checks", "if", "a", "civilization", "was", "added", "in", "the", "Age", "of", "Conquerors", "expansion", "." ]
daec4916d04a73cf89f9325ad77bfaf0644fda06
https://github.com/goto-bus-stop/recanalyst/blob/daec4916d04a73cf89f9325ad77bfaf0644fda06/src/ResourcePacks/AgeOfEmpires/Civilization.php#L110-L119
train
goto-bus-stop/recanalyst
src/ResourcePacks/AgeOfEmpires/Civilization.php
Civilization.isForgottenCiv
public static function isForgottenCiv($id) { return in_array($id, [ self::ITALIANS, self::INDIANS, self::INCAS, self::MAGYARS, self::SLAVS, ]); }
php
public static function isForgottenCiv($id) { return in_array($id, [ self::ITALIANS, self::INDIANS, self::INCAS, self::MAGYARS, self::SLAVS, ]); }
[ "public", "static", "function", "isForgottenCiv", "(", "$", "id", ")", "{", "return", "in_array", "(", "$", "id", ",", "[", "self", "::", "ITALIANS", ",", "self", "::", "INDIANS", ",", "self", "::", "INCAS", ",", "self", "::", "MAGYARS", ",", "self", ...
Checks if a civilization was added in the Forgotten Empires expansion. @param int $id Civilization ID. @return bool True if the given civilization is part of The Forgotten, false otherwise.
[ "Checks", "if", "a", "civilization", "was", "added", "in", "the", "Forgotten", "Empires", "expansion", "." ]
daec4916d04a73cf89f9325ad77bfaf0644fda06
https://github.com/goto-bus-stop/recanalyst/blob/daec4916d04a73cf89f9325ad77bfaf0644fda06/src/ResourcePacks/AgeOfEmpires/Civilization.php#L128-L137
train
goto-bus-stop/recanalyst
src/Processors/MapName.php
MapName.run
public function run() { $header = $this->rec->header(); $messages = $header->messages; $instructions = $messages->instructions; $lines = explode("\n", $instructions); foreach ($lines as $line) { // We don't know what language the game was played in, so we try // every language we know. foreach ($this->mapTypeRegexes as $rx) { $matches = []; if (preg_match($rx, $line, $matches)) { return $matches[1]; } } } }
php
public function run() { $header = $this->rec->header(); $messages = $header->messages; $instructions = $messages->instructions; $lines = explode("\n", $instructions); foreach ($lines as $line) { // We don't know what language the game was played in, so we try // every language we know. foreach ($this->mapTypeRegexes as $rx) { $matches = []; if (preg_match($rx, $line, $matches)) { return $matches[1]; } } } }
[ "public", "function", "run", "(", ")", "{", "$", "header", "=", "$", "this", "->", "rec", "->", "header", "(", ")", ";", "$", "messages", "=", "$", "header", "->", "messages", ";", "$", "instructions", "=", "$", "messages", "->", "instructions", ";",...
Run the processor. @return string|null The map name, if found.
[ "Run", "the", "processor", "." ]
daec4916d04a73cf89f9325ad77bfaf0644fda06
https://github.com/goto-bus-stop/recanalyst/blob/daec4916d04a73cf89f9325ad77bfaf0644fda06/src/Processors/MapName.php#L68-L84
train
goto-bus-stop/recanalyst
src/Analyzers/BodyAnalyzer.php
BodyAnalyzer.processGameStart
private function processGameStart() { $this->syncChecksumInterval = $this->readBody('l', 4); if ($this->version->isMgl) { // not sure what difference is vs mgx and up $this->position += 28; $ver = ord($this->body[$this->position]); $this->position += 4; } else { // These are also stored in the header. $isMultiplayer = $this->readBody('l', 4); $pov = $this->readBody('l', 4); $revealMap = $this->readBody('l', 4); $this->containsSequenceNumbers = $this->readBody('l', 4); $this->numberOfChapters = $this->readBody('l', 4); } }
php
private function processGameStart() { $this->syncChecksumInterval = $this->readBody('l', 4); if ($this->version->isMgl) { // not sure what difference is vs mgx and up $this->position += 28; $ver = ord($this->body[$this->position]); $this->position += 4; } else { // These are also stored in the header. $isMultiplayer = $this->readBody('l', 4); $pov = $this->readBody('l', 4); $revealMap = $this->readBody('l', 4); $this->containsSequenceNumbers = $this->readBody('l', 4); $this->numberOfChapters = $this->readBody('l', 4); } }
[ "private", "function", "processGameStart", "(", ")", "{", "$", "this", "->", "syncChecksumInterval", "=", "$", "this", "->", "readBody", "(", "'l'", ",", "4", ")", ";", "if", "(", "$", "this", "->", "version", "->", "isMgl", ")", "{", "// not sure what d...
Process the game start data.
[ "Process", "the", "game", "start", "data", "." ]
daec4916d04a73cf89f9325ad77bfaf0644fda06
https://github.com/goto-bus-stop/recanalyst/blob/daec4916d04a73cf89f9325ad77bfaf0644fda06/src/Analyzers/BodyAnalyzer.php#L393-L409
train
goto-bus-stop/recanalyst
src/Analyzers/BodyAnalyzer.php
BodyAnalyzer.processChatMessage
private function processChatMessage() { $length = $this->readBody('l', 4); if ($length <= 0) { return; } $chat = $this->readBodyRaw($length); // Chat messages are stored as "@#%dPlayerName: Message", where %d is a // digit from 1 to 8 indicating player's index (or colour). if ($chat[0] == '@' && $chat[1] == '#' && $chat[2] >= '1' && $chat[2] <= '8') { $chat = rtrim($chat); // Remove null terminator if (substr($chat, 3, 2) == '--' && substr($chat, -2) == '--') { // Skip messages like "--Warning: You are under attack... --" return; } else if (!empty($this->playersByNumber[$chat[2]])) { $player = $this->playersByNumber[$chat[2]]; } else { // Shouldn't happen, but we'll let the ChatMessage factory // create a fake player for this message. // TODO that auto-create behaviour is probably not desirable… $player = null; } $this->chatMessages[] = ChatMessage::create( $this->currentTime, $player, substr($chat, 3) ); } }
php
private function processChatMessage() { $length = $this->readBody('l', 4); if ($length <= 0) { return; } $chat = $this->readBodyRaw($length); // Chat messages are stored as "@#%dPlayerName: Message", where %d is a // digit from 1 to 8 indicating player's index (or colour). if ($chat[0] == '@' && $chat[1] == '#' && $chat[2] >= '1' && $chat[2] <= '8') { $chat = rtrim($chat); // Remove null terminator if (substr($chat, 3, 2) == '--' && substr($chat, -2) == '--') { // Skip messages like "--Warning: You are under attack... --" return; } else if (!empty($this->playersByNumber[$chat[2]])) { $player = $this->playersByNumber[$chat[2]]; } else { // Shouldn't happen, but we'll let the ChatMessage factory // create a fake player for this message. // TODO that auto-create behaviour is probably not desirable… $player = null; } $this->chatMessages[] = ChatMessage::create( $this->currentTime, $player, substr($chat, 3) ); } }
[ "private", "function", "processChatMessage", "(", ")", "{", "$", "length", "=", "$", "this", "->", "readBody", "(", "'l'", ",", "4", ")", ";", "if", "(", "$", "length", "<=", "0", ")", "{", "return", ";", "}", "$", "chat", "=", "$", "this", "->",...
Read a chat message.
[ "Read", "a", "chat", "message", "." ]
daec4916d04a73cf89f9325ad77bfaf0644fda06
https://github.com/goto-bus-stop/recanalyst/blob/daec4916d04a73cf89f9325ad77bfaf0644fda06/src/Analyzers/BodyAnalyzer.php#L414-L443
train
goto-bus-stop/recanalyst
src/Analyzers/HeaderAnalyzer.php
HeaderAnalyzer.readChat
protected function readChat(array $players) { $playersByNumber = []; foreach ($players as $player) { $playersByNumber[$player->number] = $player; } $messages = []; $messageCount = $this->readHeader('l', 4); for ($i = 0; $i < $messageCount; $i += 1) { $length = $this->readHeader('l', 4); if ($length <= 0) { continue; } $chat = $this->readHeaderRaw($length); // pre-game chat messages are stored as "@#%dPlayerName: Message", // where %d is a digit from 1 to 8 indicating player's index (or // colour) if ($chat[0] == '@' && $chat[1] == '#' && $chat[2] >= '1' && $chat[2] <= '8') { $chat = rtrim($chat); // throw null-termination character if (!empty($playersByNumber[$chat[2]])) { $player = $playersByNumber[$chat[2]]; } else { // this player left before the game started $player = null; } $messages[] = ChatMessage::create(null, $player, substr($chat, 3)); } } return $messages; }
php
protected function readChat(array $players) { $playersByNumber = []; foreach ($players as $player) { $playersByNumber[$player->number] = $player; } $messages = []; $messageCount = $this->readHeader('l', 4); for ($i = 0; $i < $messageCount; $i += 1) { $length = $this->readHeader('l', 4); if ($length <= 0) { continue; } $chat = $this->readHeaderRaw($length); // pre-game chat messages are stored as "@#%dPlayerName: Message", // where %d is a digit from 1 to 8 indicating player's index (or // colour) if ($chat[0] == '@' && $chat[1] == '#' && $chat[2] >= '1' && $chat[2] <= '8') { $chat = rtrim($chat); // throw null-termination character if (!empty($playersByNumber[$chat[2]])) { $player = $playersByNumber[$chat[2]]; } else { // this player left before the game started $player = null; } $messages[] = ChatMessage::create(null, $player, substr($chat, 3)); } } return $messages; }
[ "protected", "function", "readChat", "(", "array", "$", "players", ")", "{", "$", "playersByNumber", "=", "[", "]", ";", "foreach", "(", "$", "players", "as", "$", "player", ")", "{", "$", "playersByNumber", "[", "$", "player", "->", "number", "]", "="...
Read a block containing chat messages. Chat block structure: int32 count; ChatMessage messages[count]; Chat message structure: int32 length; char contents[length]; Not much data is encoded in the chat message structure, so we derive a lot of it from the `contents` string instead. @param array $players Array of `$playerId => $playerObject`, used to associate player objects with chat messages. @return array
[ "Read", "a", "block", "containing", "chat", "messages", "." ]
daec4916d04a73cf89f9325ad77bfaf0644fda06
https://github.com/goto-bus-stop/recanalyst/blob/daec4916d04a73cf89f9325ad77bfaf0644fda06/src/Analyzers/HeaderAnalyzer.php#L269-L300
train
goto-bus-stop/recanalyst
src/Analyzers/HeaderAnalyzer.php
HeaderAnalyzer.skipTriggerInfo
protected function skipTriggerInfo() { // Effects and triggers are of variable size, but conditions are // constant. $conditionSize = ( (11 * 4) + // 11 ints (4 * 4) + // area (4 ints) (3 * 4) // 3 ints ); if ($this->version->isHDPatch4) { $conditionSize += 2 * 4; // 2 ints } $numTriggers = $this->readHeader('l', 4); for ($i = 0; $i < $numTriggers; $i += 1) { $this->position += 4 + (2 * 1) + (3 * 4); // int, 2 bools, 3 ints $descriptionLength = $this->readHeader('l', 4); // HD edition 4.x saves a length of -1 when the string is absent, // whereas older versions would use 0. That used to work fine // without this guard, but now we should only skip if the length is // positive. if ($descriptionLength > 0) { $this->position += $descriptionLength; } $nameLength = $this->readHeader('l', 4); if ($nameLength > 0) { $this->position += $nameLength; } $numEffects = $this->readHeader('l', 4); for ($j = 0; $j < $numEffects; $j += 1) { $this->position += 6 * 4; // 6 ints $numSelectedObjects = $this->readHeader('l', 4); if ($numSelectedObjects === -1) { $numSelectedObjects = 0; } $this->position += 9 * 4; // 9 ints $this->position += 2 * 4; // location (2 ints) $this->position += 4 * 4; // area (2 locations) $this->position += 3 * 4; // 3 ints if ($this->version->isHDPatch4) { $this->position += 4; // int for the new Attack Stance effect } $textLength = $this->readHeader('l', 4); if ($textLength > 0) { $this->position += $textLength; } $soundFileNameLength = $this->readHeader('l', 4); if ($soundFileNameLength > 0) { $this->position += $soundFileNameLength; } $this->position += $numSelectedObjects * 4; // unit IDs (one int each) } $this->position += $numEffects * 4; // effect order (list of ints) $numConditions = $this->readHeader('l', 4); $this->position += $numConditions * $conditionSize; // conditions $this->position += $numConditions * 4; // conditions order (list of ints) } if ($numTriggers > 0) { $this->position += $numTriggers * 4; // trigger order (list of ints) // TODO perhaps also set game type to Scenario here? } }
php
protected function skipTriggerInfo() { // Effects and triggers are of variable size, but conditions are // constant. $conditionSize = ( (11 * 4) + // 11 ints (4 * 4) + // area (4 ints) (3 * 4) // 3 ints ); if ($this->version->isHDPatch4) { $conditionSize += 2 * 4; // 2 ints } $numTriggers = $this->readHeader('l', 4); for ($i = 0; $i < $numTriggers; $i += 1) { $this->position += 4 + (2 * 1) + (3 * 4); // int, 2 bools, 3 ints $descriptionLength = $this->readHeader('l', 4); // HD edition 4.x saves a length of -1 when the string is absent, // whereas older versions would use 0. That used to work fine // without this guard, but now we should only skip if the length is // positive. if ($descriptionLength > 0) { $this->position += $descriptionLength; } $nameLength = $this->readHeader('l', 4); if ($nameLength > 0) { $this->position += $nameLength; } $numEffects = $this->readHeader('l', 4); for ($j = 0; $j < $numEffects; $j += 1) { $this->position += 6 * 4; // 6 ints $numSelectedObjects = $this->readHeader('l', 4); if ($numSelectedObjects === -1) { $numSelectedObjects = 0; } $this->position += 9 * 4; // 9 ints $this->position += 2 * 4; // location (2 ints) $this->position += 4 * 4; // area (2 locations) $this->position += 3 * 4; // 3 ints if ($this->version->isHDPatch4) { $this->position += 4; // int for the new Attack Stance effect } $textLength = $this->readHeader('l', 4); if ($textLength > 0) { $this->position += $textLength; } $soundFileNameLength = $this->readHeader('l', 4); if ($soundFileNameLength > 0) { $this->position += $soundFileNameLength; } $this->position += $numSelectedObjects * 4; // unit IDs (one int each) } $this->position += $numEffects * 4; // effect order (list of ints) $numConditions = $this->readHeader('l', 4); $this->position += $numConditions * $conditionSize; // conditions $this->position += $numConditions * 4; // conditions order (list of ints) } if ($numTriggers > 0) { $this->position += $numTriggers * 4; // trigger order (list of ints) // TODO perhaps also set game type to Scenario here? } }
[ "protected", "function", "skipTriggerInfo", "(", ")", "{", "// Effects and triggers are of variable size, but conditions are", "// constant.", "$", "conditionSize", "=", "(", "(", "11", "*", "4", ")", "+", "// 11 ints", "(", "4", "*", "4", ")", "+", "// area (4 ints...
Skip a scenario triggers info block. See ScenarioTriggersAnalyzer for contents of a trigger block.
[ "Skip", "a", "scenario", "triggers", "info", "block", ".", "See", "ScenarioTriggersAnalyzer", "for", "contents", "of", "a", "trigger", "block", "." ]
daec4916d04a73cf89f9325ad77bfaf0644fda06
https://github.com/goto-bus-stop/recanalyst/blob/daec4916d04a73cf89f9325ad77bfaf0644fda06/src/Analyzers/HeaderAnalyzer.php#L374-L437
train
goto-bus-stop/recanalyst
src/Analyzers/HeaderAnalyzer.php
HeaderAnalyzer.readScenarioHeader
protected function readScenarioHeader() { $nextUnitId = $this->readHeader('l', 4); $this->position += 4; // Player names for ($i = 0; $i < 16; $i++) { $this->position += 256; // rtrim(readHeaderRaw(), \0) } // Player names (string table) for ($i = 0; $i < 16; $i++) { $this->position += 4; // int } for ($i = 0; $i < 16; $i++) { $this->position += 4; // bool isActive $this->position += 4; // bool isHuman $this->position += 4; // int civilization $this->position += 4; // const 0x00000004 } $this->position += 5; $elapsedTime = $this->readHeader('f', 4); $nameLen = $this->readHeader('v', 2); $filename = $this->readHeaderRaw($nameLen); // These should be string IDs for messages? if ($this->version->isMgl) { $this->position += 20; } else { $this->position += 24; } $this->analysis->scenarioFilename = $filename; }
php
protected function readScenarioHeader() { $nextUnitId = $this->readHeader('l', 4); $this->position += 4; // Player names for ($i = 0; $i < 16; $i++) { $this->position += 256; // rtrim(readHeaderRaw(), \0) } // Player names (string table) for ($i = 0; $i < 16; $i++) { $this->position += 4; // int } for ($i = 0; $i < 16; $i++) { $this->position += 4; // bool isActive $this->position += 4; // bool isHuman $this->position += 4; // int civilization $this->position += 4; // const 0x00000004 } $this->position += 5; $elapsedTime = $this->readHeader('f', 4); $nameLen = $this->readHeader('v', 2); $filename = $this->readHeaderRaw($nameLen); // These should be string IDs for messages? if ($this->version->isMgl) { $this->position += 20; } else { $this->position += 24; } $this->analysis->scenarioFilename = $filename; }
[ "protected", "function", "readScenarioHeader", "(", ")", "{", "$", "nextUnitId", "=", "$", "this", "->", "readHeader", "(", "'l'", ",", "4", ")", ";", "$", "this", "->", "position", "+=", "4", ";", "// Player names", "for", "(", "$", "i", "=", "0", "...
Read the scenario info header. Contains information about configured players and the scenario file. @return void
[ "Read", "the", "scenario", "info", "header", ".", "Contains", "information", "about", "configured", "players", "and", "the", "scenario", "file", "." ]
daec4916d04a73cf89f9325ad77bfaf0644fda06
https://github.com/goto-bus-stop/recanalyst/blob/daec4916d04a73cf89f9325ad77bfaf0644fda06/src/Analyzers/HeaderAnalyzer.php#L445-L477
train
goto-bus-stop/recanalyst
src/Analyzers/HeaderAnalyzer.php
HeaderAnalyzer.readMessages
protected function readMessages() { $len = $this->readHeader('v', 2); $instructions = rtrim($this->readHeaderRaw($len), "\0"); $len = $this->readHeader('v', 2); $hints = rtrim($this->readHeaderRaw($len), "\0"); $len = $this->readHeader('v', 2); $victory = rtrim($this->readHeaderRaw($len), "\0"); $len = $this->readHeader('v', 2); $loss = rtrim($this->readHeaderRaw($len), "\0"); $len = $this->readHeader('v', 2); $history = rtrim($this->readHeaderRaw($len), "\0"); $len = $this->readHeader('v', 2); $scouts = rtrim($this->readHeaderRaw($len), "\0"); return (object) [ 'instructions' => $instructions, 'hints' => $hints, 'victory' => $victory, 'loss' => $loss, 'history' => $history, 'scouts' => $scouts, ]; }
php
protected function readMessages() { $len = $this->readHeader('v', 2); $instructions = rtrim($this->readHeaderRaw($len), "\0"); $len = $this->readHeader('v', 2); $hints = rtrim($this->readHeaderRaw($len), "\0"); $len = $this->readHeader('v', 2); $victory = rtrim($this->readHeaderRaw($len), "\0"); $len = $this->readHeader('v', 2); $loss = rtrim($this->readHeaderRaw($len), "\0"); $len = $this->readHeader('v', 2); $history = rtrim($this->readHeaderRaw($len), "\0"); $len = $this->readHeader('v', 2); $scouts = rtrim($this->readHeaderRaw($len), "\0"); return (object) [ 'instructions' => $instructions, 'hints' => $hints, 'victory' => $victory, 'loss' => $loss, 'history' => $history, 'scouts' => $scouts, ]; }
[ "protected", "function", "readMessages", "(", ")", "{", "$", "len", "=", "$", "this", "->", "readHeader", "(", "'v'", ",", "2", ")", ";", "$", "instructions", "=", "rtrim", "(", "$", "this", "->", "readHeaderRaw", "(", "$", "len", ")", ",", "\"\\0\""...
Read messages. @return \StdClass
[ "Read", "messages", "." ]
daec4916d04a73cf89f9325ad77bfaf0644fda06
https://github.com/goto-bus-stop/recanalyst/blob/daec4916d04a73cf89f9325ad77bfaf0644fda06/src/Analyzers/HeaderAnalyzer.php#L484-L506
train
goto-bus-stop/recanalyst
src/Analyzers/HeaderAnalyzer.php
HeaderAnalyzer.buildTeams
protected function buildTeams($players) { $teams = []; $teamsByIndex = []; foreach ($players as $player) { /** * Team = 0 can mean two things: either this player has no team, * i.e. is in a team on their own, or this player is cooping with * another player who _is_ part of a team. */ if ($player->team == 0) { $found = false; foreach ($teams as $team) { if ($team->index() != $player->team) { continue; } foreach ($team->players() as $coopPlayer) { if ($coopPlayer->index == $player->index) { $team->addPlayer($player); $found = true; break; } } } // Not a cooping player, so add them to their own team. if (!$found) { $team = new Team(); $team->addPlayer($player); $teams[] = $team; $teamsByIndex[$player->team] = $team; } } else { if (array_key_exists($player->team, $teamsByIndex)) { $teamsByIndex[$player->team]->addPlayer($player); } else { $team = new Team(); $team ->addPlayer($player); $teams[] = $team; $teamsByIndex[$player->team] = $team; } } } return $teams; }
php
protected function buildTeams($players) { $teams = []; $teamsByIndex = []; foreach ($players as $player) { /** * Team = 0 can mean two things: either this player has no team, * i.e. is in a team on their own, or this player is cooping with * another player who _is_ part of a team. */ if ($player->team == 0) { $found = false; foreach ($teams as $team) { if ($team->index() != $player->team) { continue; } foreach ($team->players() as $coopPlayer) { if ($coopPlayer->index == $player->index) { $team->addPlayer($player); $found = true; break; } } } // Not a cooping player, so add them to their own team. if (!$found) { $team = new Team(); $team->addPlayer($player); $teams[] = $team; $teamsByIndex[$player->team] = $team; } } else { if (array_key_exists($player->team, $teamsByIndex)) { $teamsByIndex[$player->team]->addPlayer($player); } else { $team = new Team(); $team ->addPlayer($player); $teams[] = $team; $teamsByIndex[$player->team] = $team; } } } return $teams; }
[ "protected", "function", "buildTeams", "(", "$", "players", ")", "{", "$", "teams", "=", "[", "]", ";", "$", "teamsByIndex", "=", "[", "]", ";", "foreach", "(", "$", "players", "as", "$", "player", ")", "{", "/**\n * Team = 0 can mean two things:...
Group players into teams. @param \RecAnalyst\Model\Player[] $players Array of players. @return \RecAnalyst\Model\Team[]
[ "Group", "players", "into", "teams", "." ]
daec4916d04a73cf89f9325ad77bfaf0644fda06
https://github.com/goto-bus-stop/recanalyst/blob/daec4916d04a73cf89f9325ad77bfaf0644fda06/src/Analyzers/HeaderAnalyzer.php#L515-L559
train
goto-bus-stop/recanalyst
src/Analyzers/VersionAnalyzer.php
VersionAnalyzer.run
protected function run() { $versionString = rtrim($this->readHeaderRaw(8)); $subVersion = round($this->readHeader('f', 4), 2); $version = $this->getVersion($versionString, $subVersion); $analysis = new Version($this->rec, $versionString, $subVersion); $analysis->version = $version; $analysis->isTrial = in_array($version, $this->trialVersions); $analysis->isAoK = in_array($version, $this->aokVersions); $analysis->isUserPatch = in_array($version, $this->userpatchVersions); $analysis->isUserPatch15 = $version === Version::VERSION_USERPATCH15; $analysis->isHDEdition = in_array($version, $this->hdVersions); $analysis->isHDPatch4 = $analysis->isHDEdition && $subVersion >= 12.00; $analysis->isAoC = $analysis->isUserPatch || $analysis->isHDEdition || in_array($version, $this->aocVersions); $analysis->isMgl = $analysis->isAoK; $analysis->isMgx = $analysis->isAoC; $analysis->isMgz = $analysis->isUserPatch; // FIXME Not sure if this is the correct cutoff point. // // test/recs/versions/mgx2_simple.mgx2 // has subVersion == 12.31 // test/recs/versions/MP Replay v4.3 @2015.09.11 221142 (2).msx // has subVersion == 12.34 // So it's somewhere between those two. $analysis->isMsx = $subVersion >= 12.32; $analysis->isAoe2Record = $subVersion >= 12.36; return $analysis; }
php
protected function run() { $versionString = rtrim($this->readHeaderRaw(8)); $subVersion = round($this->readHeader('f', 4), 2); $version = $this->getVersion($versionString, $subVersion); $analysis = new Version($this->rec, $versionString, $subVersion); $analysis->version = $version; $analysis->isTrial = in_array($version, $this->trialVersions); $analysis->isAoK = in_array($version, $this->aokVersions); $analysis->isUserPatch = in_array($version, $this->userpatchVersions); $analysis->isUserPatch15 = $version === Version::VERSION_USERPATCH15; $analysis->isHDEdition = in_array($version, $this->hdVersions); $analysis->isHDPatch4 = $analysis->isHDEdition && $subVersion >= 12.00; $analysis->isAoC = $analysis->isUserPatch || $analysis->isHDEdition || in_array($version, $this->aocVersions); $analysis->isMgl = $analysis->isAoK; $analysis->isMgx = $analysis->isAoC; $analysis->isMgz = $analysis->isUserPatch; // FIXME Not sure if this is the correct cutoff point. // // test/recs/versions/mgx2_simple.mgx2 // has subVersion == 12.31 // test/recs/versions/MP Replay v4.3 @2015.09.11 221142 (2).msx // has subVersion == 12.34 // So it's somewhere between those two. $analysis->isMsx = $subVersion >= 12.32; $analysis->isAoe2Record = $subVersion >= 12.36; return $analysis; }
[ "protected", "function", "run", "(", ")", "{", "$", "versionString", "=", "rtrim", "(", "$", "this", "->", "readHeaderRaw", "(", "8", ")", ")", ";", "$", "subVersion", "=", "round", "(", "$", "this", "->", "readHeader", "(", "'f'", ",", "4", ")", "...
Read recorded game version metadata. Recorded game version information is encoded as: char version[8]; // something like "VER 9.C\0" float subVersion; @return object
[ "Read", "recorded", "game", "version", "metadata", "." ]
daec4916d04a73cf89f9325ad77bfaf0644fda06
https://github.com/goto-bus-stop/recanalyst/blob/daec4916d04a73cf89f9325ad77bfaf0644fda06/src/Analyzers/VersionAnalyzer.php#L86-L119
train
goto-bus-stop/recanalyst
src/Analyzers/VersionAnalyzer.php
VersionAnalyzer.getVersion
private function getVersion($version, $subVersion) { switch ($version) { case 'TRL 9.3': return $this->isMgx ? Version::VERSION_AOCTRIAL : Version::VERSION_AOKTRIAL; case 'VER 9.3': return Version::VERSION_AOK; case 'VER 9.4': if ($subVersion >= 12.50) { return Version::VERSION_HD50; } if ($subVersion >= 12.49) { return Version::VERSION_HD48; } if ($subVersion >= 12.36) { // Patch versions 4.6 and 4.7. return Version::VERSION_HD46; } if ($subVersion >= 12.34) { // Probably versions 4.3 through 4.5? return Version::VERSION_HD43; } if ($subVersion > 11.76) { return Version::VERSION_HD; } return Version::VERSION_AOC; case 'VER 9.5': return Version::VERSION_AOFE21; case 'VER 9.8': return Version::VERSION_USERPATCH12; case 'VER 9.9': return Version::VERSION_USERPATCH13; // UserPatch 1.4 RC 1 case 'VER 9.A': // UserPatch 1.4 RC 2 case 'VER 9.B': case 'VER 9.C': case 'VER 9.D': return Version::VERSION_USERPATCH14; case 'VER 9.E': case 'VER 9.F': return Version::VERSION_USERPATCH15; default: return $version; } }
php
private function getVersion($version, $subVersion) { switch ($version) { case 'TRL 9.3': return $this->isMgx ? Version::VERSION_AOCTRIAL : Version::VERSION_AOKTRIAL; case 'VER 9.3': return Version::VERSION_AOK; case 'VER 9.4': if ($subVersion >= 12.50) { return Version::VERSION_HD50; } if ($subVersion >= 12.49) { return Version::VERSION_HD48; } if ($subVersion >= 12.36) { // Patch versions 4.6 and 4.7. return Version::VERSION_HD46; } if ($subVersion >= 12.34) { // Probably versions 4.3 through 4.5? return Version::VERSION_HD43; } if ($subVersion > 11.76) { return Version::VERSION_HD; } return Version::VERSION_AOC; case 'VER 9.5': return Version::VERSION_AOFE21; case 'VER 9.8': return Version::VERSION_USERPATCH12; case 'VER 9.9': return Version::VERSION_USERPATCH13; // UserPatch 1.4 RC 1 case 'VER 9.A': // UserPatch 1.4 RC 2 case 'VER 9.B': case 'VER 9.C': case 'VER 9.D': return Version::VERSION_USERPATCH14; case 'VER 9.E': case 'VER 9.F': return Version::VERSION_USERPATCH15; default: return $version; } }
[ "private", "function", "getVersion", "(", "$", "version", ",", "$", "subVersion", ")", "{", "switch", "(", "$", "version", ")", "{", "case", "'TRL 9.3'", ":", "return", "$", "this", "->", "isMgx", "?", "Version", "::", "VERSION_AOCTRIAL", ":", "Version", ...
Get the version ID from a version string and sub-version number. @param string $version Version string, found at the start of the file header. @param float $subVersion Sub-version number. @return int Game version ID.
[ "Get", "the", "version", "ID", "from", "a", "version", "string", "and", "sub", "-", "version", "number", "." ]
daec4916d04a73cf89f9325ad77bfaf0644fda06
https://github.com/goto-bus-stop/recanalyst/blob/daec4916d04a73cf89f9325ad77bfaf0644fda06/src/Analyzers/VersionAnalyzer.php#L129-L174
train
goto-bus-stop/recanalyst
src/ResourcePacks/AgeOfEmpires/Map.php
Map.isRealWorldMap
public static function isRealWorldMap($id) { return in_array($id, [ self::IBERIA, self::BRITAIN, self::MIDEAST, self::TEXAS, self::ITALY, self::CENTRALAMERICA, self::FRANCE, self::NORSELANDS, self::SEAOFJAPAN, self::BYZANTINUM, ]); }
php
public static function isRealWorldMap($id) { return in_array($id, [ self::IBERIA, self::BRITAIN, self::MIDEAST, self::TEXAS, self::ITALY, self::CENTRALAMERICA, self::FRANCE, self::NORSELANDS, self::SEAOFJAPAN, self::BYZANTINUM, ]); }
[ "public", "static", "function", "isRealWorldMap", "(", "$", "id", ")", "{", "return", "in_array", "(", "$", "id", ",", "[", "self", "::", "IBERIA", ",", "self", "::", "BRITAIN", ",", "self", "::", "MIDEAST", ",", "self", "::", "TEXAS", ",", "self", "...
Check whether a builtin map is a "Real World" map, such as Byzantinum or Texas. @param int $id Map ID of a builtin map. @return bool True if the map is a "Real World" map, false otherwise.
[ "Check", "whether", "a", "builtin", "map", "is", "a", "Real", "World", "map", "such", "as", "Byzantinum", "or", "Texas", "." ]
daec4916d04a73cf89f9325ad77bfaf0644fda06
https://github.com/goto-bus-stop/recanalyst/blob/daec4916d04a73cf89f9325ad77bfaf0644fda06/src/ResourcePacks/AgeOfEmpires/Map.php#L73-L80
train
goto-bus-stop/recanalyst
src/ResourcePacks/AgeOfEmpires/Map.php
Map.isStandardMap
public static function isStandardMap($id) { return in_array($id, [ self::ARABIA, self::ARCHIPELAGO, self::BALTIC, self::BLACKFOREST, self::COASTAL, self::CONTINENTAL, self::CRATERLAKE, self::FORTRESS, self::GOLDRUSH, self::HIGHLAND, self::ISLANDS, self::MEDITERRANEAN, self::MIGRATION, self::RIVERS, self::TEAMISLANDS, self::SCANDINAVIA, self::MONGOLIA, self::YUCATAN, self::SALTMARSH, self::ARENA, self::KINGOFTHEHILL, self::OASIS, self::GHOSTLAKE, self::NOMAD, self::RANDOM, ]); }
php
public static function isStandardMap($id) { return in_array($id, [ self::ARABIA, self::ARCHIPELAGO, self::BALTIC, self::BLACKFOREST, self::COASTAL, self::CONTINENTAL, self::CRATERLAKE, self::FORTRESS, self::GOLDRUSH, self::HIGHLAND, self::ISLANDS, self::MEDITERRANEAN, self::MIGRATION, self::RIVERS, self::TEAMISLANDS, self::SCANDINAVIA, self::MONGOLIA, self::YUCATAN, self::SALTMARSH, self::ARENA, self::KINGOFTHEHILL, self::OASIS, self::GHOSTLAKE, self::NOMAD, self::RANDOM, ]); }
[ "public", "static", "function", "isStandardMap", "(", "$", "id", ")", "{", "return", "in_array", "(", "$", "id", ",", "[", "self", "::", "ARABIA", ",", "self", "::", "ARCHIPELAGO", ",", "self", "::", "BALTIC", ",", "self", "::", "BLACKFOREST", ",", "se...
Check whether a map ID denotes a builtin map. @see \RecAnalyst\ResourcePacks\AgeOfEmpires::isCustomMap For the inverse. @param int $id Map ID. @return bool True if the map is builtin, false otherwise.
[ "Check", "whether", "a", "map", "ID", "denotes", "a", "builtin", "map", "." ]
daec4916d04a73cf89f9325ad77bfaf0644fda06
https://github.com/goto-bus-stop/recanalyst/blob/daec4916d04a73cf89f9325ad77bfaf0644fda06/src/ResourcePacks/AgeOfEmpires/Map.php#L103-L115
train
goto-bus-stop/recanalyst
src/StreamExtractor.php
StreamExtractor.manuallyDetermineHeaderLength
private function manuallyDetermineHeaderLength() { // This separator is part of the Start Game command, which is the very // first command in the recorded game body. It's … reasonably accurate. $separator = pack('c*', 0xF4, 0x01, 0x00, 0x00); // We need to reset the file pointer when we're done $initialBase = ftell($this->fp); $base = $initialBase; $buffer = ''; while (($buffer = fread($this->fp, 8192)) !== false) { $index = strpos($buffer, $separator); if ($index !== false) { $this->headerLen = $base + $index - 4; break; } $base += strlen($buffer); } fseek($this->fp, $initialBase); }
php
private function manuallyDetermineHeaderLength() { // This separator is part of the Start Game command, which is the very // first command in the recorded game body. It's … reasonably accurate. $separator = pack('c*', 0xF4, 0x01, 0x00, 0x00); // We need to reset the file pointer when we're done $initialBase = ftell($this->fp); $base = $initialBase; $buffer = ''; while (($buffer = fread($this->fp, 8192)) !== false) { $index = strpos($buffer, $separator); if ($index !== false) { $this->headerLen = $base + $index - 4; break; } $base += strlen($buffer); } fseek($this->fp, $initialBase); }
[ "private", "function", "manuallyDetermineHeaderLength", "(", ")", "{", "// This separator is part of the Start Game command, which is the very", "// first command in the recorded game body. It's … reasonably accurate.", "$", "separator", "=", "pack", "(", "'c*'", ",", "0xF4", ",", ...
Determine the header length if the Header Length field was not set in the file.
[ "Determine", "the", "header", "length", "if", "the", "Header", "Length", "field", "was", "not", "set", "in", "the", "file", "." ]
daec4916d04a73cf89f9325ad77bfaf0644fda06
https://github.com/goto-bus-stop/recanalyst/blob/daec4916d04a73cf89f9325ad77bfaf0644fda06/src/StreamExtractor.php#L73-L92
train
goto-bus-stop/recanalyst
src/StreamExtractor.php
StreamExtractor.determineHeaderLength
private function determineHeaderLength() { $rawRead = fread($this->fp, 4); if ($rawRead === false || strlen($rawRead) < 4) { throw new RecAnalystException( 'Unable to read the header length', RecAnalystException::HEADERLEN_READERROR ); } list (, $this->headerLen) = unpack('V', $rawRead); if (!$this->headerLen) { $this->manuallyDetermineHeaderLength(); } if (!$this->headerLen) { throw new RecAnalystException( 'Header length is zero', RecAnalystException::EMPTY_HEADER ); } // In MGL files, the header starts immediately after the header length // bytes. In MGX files, another int32 is stored first, possibly indicating // the position of possible further headers(? something for saved chapters, // at least, or perhaps saved & restored games). // The gzip-compressed header always starts with a series of bytes that // decodes to a really high number. So if the next 4 bytes _don't_ // encode to a really high number, they must refer to the next header. $rawRead = fread($this->fp, 4); list (, $nextPos) = unpack('V', $rawRead); $hasNextPos = $nextPos === 0 || $nextPos < $this->getFileSize(); $this->headerStart = $hasNextPos ? 8 : 4; $this->headerLen -= $this->headerStart; }
php
private function determineHeaderLength() { $rawRead = fread($this->fp, 4); if ($rawRead === false || strlen($rawRead) < 4) { throw new RecAnalystException( 'Unable to read the header length', RecAnalystException::HEADERLEN_READERROR ); } list (, $this->headerLen) = unpack('V', $rawRead); if (!$this->headerLen) { $this->manuallyDetermineHeaderLength(); } if (!$this->headerLen) { throw new RecAnalystException( 'Header length is zero', RecAnalystException::EMPTY_HEADER ); } // In MGL files, the header starts immediately after the header length // bytes. In MGX files, another int32 is stored first, possibly indicating // the position of possible further headers(? something for saved chapters, // at least, or perhaps saved & restored games). // The gzip-compressed header always starts with a series of bytes that // decodes to a really high number. So if the next 4 bytes _don't_ // encode to a really high number, they must refer to the next header. $rawRead = fread($this->fp, 4); list (, $nextPos) = unpack('V', $rawRead); $hasNextPos = $nextPos === 0 || $nextPos < $this->getFileSize(); $this->headerStart = $hasNextPos ? 8 : 4; $this->headerLen -= $this->headerStart; }
[ "private", "function", "determineHeaderLength", "(", ")", "{", "$", "rawRead", "=", "fread", "(", "$", "this", "->", "fp", ",", "4", ")", ";", "if", "(", "$", "rawRead", "===", "false", "||", "strlen", "(", "$", "rawRead", ")", "<", "4", ")", "{", ...
Find the header length.
[ "Find", "the", "header", "length", "." ]
daec4916d04a73cf89f9325ad77bfaf0644fda06
https://github.com/goto-bus-stop/recanalyst/blob/daec4916d04a73cf89f9325ad77bfaf0644fda06/src/StreamExtractor.php#L109-L141
train
goto-bus-stop/recanalyst
src/StreamExtractor.php
StreamExtractor.getHeader
public function getHeader() { if ($this->headerContents) { return $this->headerContents; } if (!$this->headerLen) { $this->determineHeaderLength(); } fseek($this->fp, $this->headerStart, SEEK_SET); $read = 0; $bindata = ''; while ($read < $this->headerLen && ($buff = fread($this->fp, $this->headerLen - $read))) { $read += strlen($buff); $bindata .= $buff; } unset($buff); $this->headerContents = gzinflate($bindata, $this->options['memoryLimit']); unset($bindata); if (!strlen($this->headerContents)) { throw new RecAnalystException( 'Cannot decompress header section', RecAnalystException::HEADER_DECOMPRESSERROR ); } return $this->headerContents; }
php
public function getHeader() { if ($this->headerContents) { return $this->headerContents; } if (!$this->headerLen) { $this->determineHeaderLength(); } fseek($this->fp, $this->headerStart, SEEK_SET); $read = 0; $bindata = ''; while ($read < $this->headerLen && ($buff = fread($this->fp, $this->headerLen - $read))) { $read += strlen($buff); $bindata .= $buff; } unset($buff); $this->headerContents = gzinflate($bindata, $this->options['memoryLimit']); unset($bindata); if (!strlen($this->headerContents)) { throw new RecAnalystException( 'Cannot decompress header section', RecAnalystException::HEADER_DECOMPRESSERROR ); } return $this->headerContents; }
[ "public", "function", "getHeader", "(", ")", "{", "if", "(", "$", "this", "->", "headerContents", ")", "{", "return", "$", "this", "->", "headerContents", ";", "}", "if", "(", "!", "$", "this", "->", "headerLen", ")", "{", "$", "this", "->", "determi...
Read or return the Recorded Game file's header block. @return string
[ "Read", "or", "return", "the", "Recorded", "Game", "file", "s", "header", "block", "." ]
daec4916d04a73cf89f9325ad77bfaf0644fda06
https://github.com/goto-bus-stop/recanalyst/blob/daec4916d04a73cf89f9325ad77bfaf0644fda06/src/StreamExtractor.php#L148-L179
train
goto-bus-stop/recanalyst
src/StreamExtractor.php
StreamExtractor.getBody
public function getBody() { if ($this->bodyContents) { return $this->bodyContents; } if (!$this->headerLen) { $this->determineHeaderLength(); } fseek($this->fp, $this->headerStart + $this->headerLen, SEEK_SET); $this->bodyContents = ''; while (!feof($this->fp)) { $this->bodyContents .= fread($this->fp, 8192); } fclose($this->fp); return $this->bodyContents; }
php
public function getBody() { if ($this->bodyContents) { return $this->bodyContents; } if (!$this->headerLen) { $this->determineHeaderLength(); } fseek($this->fp, $this->headerStart + $this->headerLen, SEEK_SET); $this->bodyContents = ''; while (!feof($this->fp)) { $this->bodyContents .= fread($this->fp, 8192); } fclose($this->fp); return $this->bodyContents; }
[ "public", "function", "getBody", "(", ")", "{", "if", "(", "$", "this", "->", "bodyContents", ")", "{", "return", "$", "this", "->", "bodyContents", ";", "}", "if", "(", "!", "$", "this", "->", "headerLen", ")", "{", "$", "this", "->", "determineHead...
Read or return the Recorded Game file's body. @return string
[ "Read", "or", "return", "the", "Recorded", "Game", "file", "s", "body", "." ]
daec4916d04a73cf89f9325ad77bfaf0644fda06
https://github.com/goto-bus-stop/recanalyst/blob/daec4916d04a73cf89f9325ad77bfaf0644fda06/src/StreamExtractor.php#L186-L205
train
goto-bus-stop/recanalyst
src/Model/VictorySettings.php
VictorySettings.getVictoryString
public function getVictoryString() { if (!isset(RecAnalystConst::$VICTORY_CONDITIONS[$this->_victoryCondition])) { return ''; } $result = RecAnalystConst::$VICTORY_CONDITIONS[$this->_victoryCondition]; switch ($this->_victoryCondition) { case self::TIMELIMIT: if ($this->_timeLimit) { return sprintf('%s (%d years)', $result, $this->_timeLimit); } break; case self::SCORELIMIT: if ($this->_scoreLimit) { return sprintf('%s (%d)', $result, $this->_scoreLimit); } break; } return $result; }
php
public function getVictoryString() { if (!isset(RecAnalystConst::$VICTORY_CONDITIONS[$this->_victoryCondition])) { return ''; } $result = RecAnalystConst::$VICTORY_CONDITIONS[$this->_victoryCondition]; switch ($this->_victoryCondition) { case self::TIMELIMIT: if ($this->_timeLimit) { return sprintf('%s (%d years)', $result, $this->_timeLimit); } break; case self::SCORELIMIT: if ($this->_scoreLimit) { return sprintf('%s (%d)', $result, $this->_scoreLimit); } break; } return $result; }
[ "public", "function", "getVictoryString", "(", ")", "{", "if", "(", "!", "isset", "(", "RecAnalystConst", "::", "$", "VICTORY_CONDITIONS", "[", "$", "this", "->", "_victoryCondition", "]", ")", ")", "{", "return", "''", ";", "}", "$", "result", "=", "Rec...
Returns victory string. @return string
[ "Returns", "victory", "string", "." ]
daec4916d04a73cf89f9325ad77bfaf0644fda06
https://github.com/goto-bus-stop/recanalyst/blob/daec4916d04a73cf89f9325ad77bfaf0644fda06/src/Model/VictorySettings.php#L64-L83
train
goto-bus-stop/recanalyst
src/Model/GameSettings.php
GameSettings.mapStyleName
public function mapStyleName() { $mapStyle = $this->rec->getResourcePack() ->getMapStyle($this->mapId); return $this->rec->trans('map_styles', $mapStyle); }
php
public function mapStyleName() { $mapStyle = $this->rec->getResourcePack() ->getMapStyle($this->mapId); return $this->rec->trans('map_styles', $mapStyle); }
[ "public", "function", "mapStyleName", "(", ")", "{", "$", "mapStyle", "=", "$", "this", "->", "rec", "->", "getResourcePack", "(", ")", "->", "getMapStyle", "(", "$", "this", "->", "mapId", ")", ";", "return", "$", "this", "->", "rec", "->", "trans", ...
Returns map style string. @return string
[ "Returns", "map", "style", "string", "." ]
daec4916d04a73cf89f9325ad77bfaf0644fda06
https://github.com/goto-bus-stop/recanalyst/blob/daec4916d04a73cf89f9325ad77bfaf0644fda06/src/Model/GameSettings.php#L145-L150
train
goto-bus-stop/recanalyst
src/Model/GameSettings.php
GameSettings.mapName
public function mapName($options = []) { $extractRmsName = isset($options['extractRMSName']) ? $options['extractRMSName'] : true; if ($extractRmsName && $this->isCustomMap()) { $nameExtractor = new MapNameExtractor($this->rec); $likelyName = $nameExtractor->run(); if ($likelyName) { return $likelyName; } } return $this->rec->trans('map_names', $this->mapId); }
php
public function mapName($options = []) { $extractRmsName = isset($options['extractRMSName']) ? $options['extractRMSName'] : true; if ($extractRmsName && $this->isCustomMap()) { $nameExtractor = new MapNameExtractor($this->rec); $likelyName = $nameExtractor->run(); if ($likelyName) { return $likelyName; } } return $this->rec->trans('map_names', $this->mapId); }
[ "public", "function", "mapName", "(", "$", "options", "=", "[", "]", ")", "{", "$", "extractRmsName", "=", "isset", "(", "$", "options", "[", "'extractRMSName'", "]", ")", "?", "$", "options", "[", "'extractRMSName'", "]", ":", "true", ";", "if", "(", ...
Get the map name. @param array $options Options. - `$options['extractRMSName']` - Whether to attempt to find the RMS file names of custom random maps. Defaults to `true`. @return string Map name.
[ "Get", "the", "map", "name", "." ]
daec4916d04a73cf89f9325ad77bfaf0644fda06
https://github.com/goto-bus-stop/recanalyst/blob/daec4916d04a73cf89f9325ad77bfaf0644fda06/src/Model/GameSettings.php#L231-L242
train
goto-bus-stop/recanalyst
src/BasicTranslator.php
BasicTranslator.get
private function get($arr, $path) { foreach (explode('.', $path) as $prop) { $arr = $arr[$prop]; } return $arr; }
php
private function get($arr, $path) { foreach (explode('.', $path) as $prop) { $arr = $arr[$prop]; } return $arr; }
[ "private", "function", "get", "(", "$", "arr", ",", "$", "path", ")", "{", "foreach", "(", "explode", "(", "'.'", ",", "$", "path", ")", "as", "$", "prop", ")", "{", "$", "arr", "=", "$", "arr", "[", "$", "prop", "]", ";", "}", "return", "$",...
Get a value from a dotted property path. @param array $arr Array. @param string $path Path, properties separated by '.'s. @return mixed (But probably a string because it's for translations.)
[ "Get", "a", "value", "from", "a", "dotted", "property", "path", "." ]
daec4916d04a73cf89f9325ad77bfaf0644fda06
https://github.com/goto-bus-stop/recanalyst/blob/daec4916d04a73cf89f9325ad77bfaf0644fda06/src/BasicTranslator.php#L66-L72
train
goto-bus-stop/recanalyst
src/Model/ChatMessage.php
ChatMessage.create
public static function create($time, $player, $chat) { $group = ''; // This is directed someplace (@All, @Team, @Enemy, etc.) // Voobly adds @Rating messages too, which we might wish to parse into // the player objects later as a `->rating` property. if ($chat[0] === '<') { // Standard directed chat messages have a format like: // <All>PlayerName: message // Voobly rating messages however: // <Rating> PlayerName: message // ...adds a space character before the name, so we deal with it // separately. if (substr($chat, 0, 9) === '<Rating> ') { $group = 'Rating'; $chat = substr($chat, 9); } else { $end = strpos($chat, '>'); $group = substr($chat, 1, $end - 1); $chat = substr($chat, $end + 1); } } if (is_null($player)) { $player = new Player(); $player->name = substr($chat, 0, strpos($chat, ': ')); if ($player->name[0] === ' ') { $player->name = substr($player->name, 1); } } // Cut the player name out of the message contents. $chat = substr($chat, strlen($player->name) + 2); return new self($time, $player, $chat, $group); }
php
public static function create($time, $player, $chat) { $group = ''; // This is directed someplace (@All, @Team, @Enemy, etc.) // Voobly adds @Rating messages too, which we might wish to parse into // the player objects later as a `->rating` property. if ($chat[0] === '<') { // Standard directed chat messages have a format like: // <All>PlayerName: message // Voobly rating messages however: // <Rating> PlayerName: message // ...adds a space character before the name, so we deal with it // separately. if (substr($chat, 0, 9) === '<Rating> ') { $group = 'Rating'; $chat = substr($chat, 9); } else { $end = strpos($chat, '>'); $group = substr($chat, 1, $end - 1); $chat = substr($chat, $end + 1); } } if (is_null($player)) { $player = new Player(); $player->name = substr($chat, 0, strpos($chat, ': ')); if ($player->name[0] === ' ') { $player->name = substr($player->name, 1); } } // Cut the player name out of the message contents. $chat = substr($chat, strlen($player->name) + 2); return new self($time, $player, $chat, $group); }
[ "public", "static", "function", "create", "(", "$", "time", ",", "$", "player", ",", "$", "chat", ")", "{", "$", "group", "=", "''", ";", "// This is directed someplace (@All, @Team, @Enemy, etc.)", "// Voobly adds @Rating messages too, which we might wish to parse into", ...
Helper method to create a chat message from a chat string more easily. Messages actually have the player name and sometimes a group specifier (<Team>, <Enemy>, etc) included in their message body which is lame. Sometimes players that don't end up in the player info blocks of the recorded games sent messages anyway (particularly pre-game chat by people who joined the multiplayer lobby and then left) so we deal with that too. @param int $time Time at which this message was sent in milliseconds since the start of the game. @param \RecAnalyst\Model\Player $player Message Sender. @param string $chat Message contents. @return ChatMessage
[ "Helper", "method", "to", "create", "a", "chat", "message", "from", "a", "chat", "string", "more", "easily", "." ]
daec4916d04a73cf89f9325ad77bfaf0644fda06
https://github.com/goto-bus-stop/recanalyst/blob/daec4916d04a73cf89f9325ad77bfaf0644fda06/src/Model/ChatMessage.php#L78-L110
train
goto-bus-stop/recanalyst
src/RecordedGame.php
RecordedGame.getAnalysis
public function getAnalysis($analyzerName, $arg = null, $startAt = 0) { $key = $analyzerName . ':' . $startAt; if (!array_key_exists($key, $this->analyses)) { $analyzer = new $analyzerName($arg); $analyzer->position = $startAt; $result = new \StdClass; $result->analysis = $this->runAnalyzer($analyzer); $result->position = $analyzer->position; $this->analyses[$key] = $result; } return $this->analyses[$key]; }
php
public function getAnalysis($analyzerName, $arg = null, $startAt = 0) { $key = $analyzerName . ':' . $startAt; if (!array_key_exists($key, $this->analyses)) { $analyzer = new $analyzerName($arg); $analyzer->position = $startAt; $result = new \StdClass; $result->analysis = $this->runAnalyzer($analyzer); $result->position = $analyzer->position; $this->analyses[$key] = $result; } return $this->analyses[$key]; }
[ "public", "function", "getAnalysis", "(", "$", "analyzerName", ",", "$", "arg", "=", "null", ",", "$", "startAt", "=", "0", ")", "{", "$", "key", "=", "$", "analyzerName", ".", "':'", ".", "$", "startAt", ";", "if", "(", "!", "array_key_exists", "(",...
Get an analysis result for a specific analyzer, running it if necessary. @param string $analyzerName Fully qualified name of the analyzer class. @param mixed $arg Optional argument to the analyzer. @param int $startAt Position to start at. @return mixed
[ "Get", "an", "analysis", "result", "for", "a", "specific", "analyzer", "running", "it", "if", "necessary", "." ]
daec4916d04a73cf89f9325ad77bfaf0644fda06
https://github.com/goto-bus-stop/recanalyst/blob/daec4916d04a73cf89f9325ad77bfaf0644fda06/src/RecordedGame.php#L136-L148
train
goto-bus-stop/recanalyst
src/RecordedGame.php
RecordedGame.getPlayer
public function getPlayer($id) { foreach ($this->header()->players as $player) { if ($player->index === $id) { return $player; } } }
php
public function getPlayer($id) { foreach ($this->header()->players as $player) { if ($player->index === $id) { return $player; } } }
[ "public", "function", "getPlayer", "(", "$", "id", ")", "{", "foreach", "(", "$", "this", "->", "header", "(", ")", "->", "players", "as", "$", "player", ")", "{", "if", "(", "$", "player", "->", "index", "===", "$", "id", ")", "{", "return", "$"...
Get a player by their index. @param int $id Player index. @return \RecAnalyst\Model\Player|null
[ "Get", "a", "player", "by", "their", "index", "." ]
daec4916d04a73cf89f9325ad77bfaf0644fda06
https://github.com/goto-bus-stop/recanalyst/blob/daec4916d04a73cf89f9325ad77bfaf0644fda06/src/RecordedGame.php#L291-L298
train
goto-bus-stop/recanalyst
src/RecordedGame.php
RecordedGame.getTranslateKey
private function getTranslateKey($args) { // Game version names are in their own file, not in with resource packs. if ($args[0] === 'game_versions') { $key = implode('.', $args); } else { $pack = get_class($this->resourcePack); $key = $pack::NAME . '.' . implode('.', $args); } if ($this->isLaravel) { return 'recanalyst::' . $key; } return $key; }
php
private function getTranslateKey($args) { // Game version names are in their own file, not in with resource packs. if ($args[0] === 'game_versions') { $key = implode('.', $args); } else { $pack = get_class($this->resourcePack); $key = $pack::NAME . '.' . implode('.', $args); } if ($this->isLaravel) { return 'recanalyst::' . $key; } return $key; }
[ "private", "function", "getTranslateKey", "(", "$", "args", ")", "{", "// Game version names are in their own file, not in with resource packs.", "if", "(", "$", "args", "[", "0", "]", "===", "'game_versions'", ")", "{", "$", "key", "=", "implode", "(", "'.'", ","...
Get a translate key for use with Symfony or Laravel Translations. @return string A translation key.
[ "Get", "a", "translate", "key", "for", "use", "with", "Symfony", "or", "Laravel", "Translations", "." ]
daec4916d04a73cf89f9325ad77bfaf0644fda06
https://github.com/goto-bus-stop/recanalyst/blob/daec4916d04a73cf89f9325ad77bfaf0644fda06/src/RecordedGame.php#L316-L329
train
goto-bus-stop/recanalyst
src/ResourcePacks/AgeOfEmpires.php
AgeOfEmpires.isGateUnit
public function isGateUnit($id) { return $id === Unit::GATE || $id === Unit::GATE2 || $id === Unit::GATE3 || $id === Unit::GATE4; }
php
public function isGateUnit($id) { return $id === Unit::GATE || $id === Unit::GATE2 || $id === Unit::GATE3 || $id === Unit::GATE4; }
[ "public", "function", "isGateUnit", "(", "$", "id", ")", "{", "return", "$", "id", "===", "Unit", "::", "GATE", "||", "$", "id", "===", "Unit", "::", "GATE2", "||", "$", "id", "===", "Unit", "::", "GATE3", "||", "$", "id", "===", "Unit", "::", "G...
Checks whether a unit type ID is a Gate unit. @param int $id Unit type ID. @return bool True if the unit type is a gate, false otherwise.
[ "Checks", "whether", "a", "unit", "type", "ID", "is", "a", "Gate", "unit", "." ]
daec4916d04a73cf89f9325ad77bfaf0644fda06
https://github.com/goto-bus-stop/recanalyst/blob/daec4916d04a73cf89f9325ad77bfaf0644fda06/src/ResourcePacks/AgeOfEmpires.php#L111-L117
train
goto-bus-stop/recanalyst
src/ResourcePacks/AgeOfEmpires.php
AgeOfEmpires.isPalisadeGateUnit
public function isPalisadeGateUnit($id) { return $id === Unit::PALISADE_GATE || $id === Unit::PALISADE_GATE2 || $id === Unit::PALISADE_GATE3 || $id === Unit::PALISADE_GATE4; }
php
public function isPalisadeGateUnit($id) { return $id === Unit::PALISADE_GATE || $id === Unit::PALISADE_GATE2 || $id === Unit::PALISADE_GATE3 || $id === Unit::PALISADE_GATE4; }
[ "public", "function", "isPalisadeGateUnit", "(", "$", "id", ")", "{", "return", "$", "id", "===", "Unit", "::", "PALISADE_GATE", "||", "$", "id", "===", "Unit", "::", "PALISADE_GATE2", "||", "$", "id", "===", "Unit", "::", "PALISADE_GATE3", "||", "$", "i...
Checks whether a unit type ID is a Palisade Gate unit. @param int $id Unit type ID. @return bool True if the unit type is a palisade gate, false otherwise.
[ "Checks", "whether", "a", "unit", "type", "ID", "is", "a", "Palisade", "Gate", "unit", "." ]
daec4916d04a73cf89f9325ad77bfaf0644fda06
https://github.com/goto-bus-stop/recanalyst/blob/daec4916d04a73cf89f9325ad77bfaf0644fda06/src/ResourcePacks/AgeOfEmpires.php#L125-L131
train
goto-bus-stop/recanalyst
src/ResourcePacks/AgeOfEmpires.php
AgeOfEmpires.isGaiaObject
public function isGaiaObject($id) { return $id >= Unit::CLIFF1 && $id <= Unit::CLIFF10 || $id === Unit::GOLDMINE || $id === Unit::STONEMINE || $id === Unit::FORAGEBUSH; }
php
public function isGaiaObject($id) { return $id >= Unit::CLIFF1 && $id <= Unit::CLIFF10 || $id === Unit::GOLDMINE || $id === Unit::STONEMINE || $id === Unit::FORAGEBUSH; }
[ "public", "function", "isGaiaObject", "(", "$", "id", ")", "{", "return", "$", "id", ">=", "Unit", "::", "CLIFF1", "&&", "$", "id", "<=", "Unit", "::", "CLIFF10", "||", "$", "id", "===", "Unit", "::", "GOLDMINE", "||", "$", "id", "===", "Unit", "::...
Checks whether a unit type ID is a GAIA object type. Used to determine which objects to draw on a map. @param int $id Unit type ID. @return bool True if the unit type is a GAIA object, false otherwise.
[ "Checks", "whether", "a", "unit", "type", "ID", "is", "a", "GAIA", "object", "type", ".", "Used", "to", "determine", "which", "objects", "to", "draw", "on", "a", "map", "." ]
daec4916d04a73cf89f9325ad77bfaf0644fda06
https://github.com/goto-bus-stop/recanalyst/blob/daec4916d04a73cf89f9325ad77bfaf0644fda06/src/ResourcePacks/AgeOfEmpires.php#L151-L157
train
goto-bus-stop/recanalyst
src/ResourcePacks/AgeOfEmpires.php
AgeOfEmpires.isGaiaUnit
public function isGaiaUnit($id) { return $id === Unit::RELIC || $id === Unit::DEER || $id === Unit::BOAR || $id === Unit::JAVELINA || $id === Unit::TURKEY || $id === Unit::SHEEP; }
php
public function isGaiaUnit($id) { return $id === Unit::RELIC || $id === Unit::DEER || $id === Unit::BOAR || $id === Unit::JAVELINA || $id === Unit::TURKEY || $id === Unit::SHEEP; }
[ "public", "function", "isGaiaUnit", "(", "$", "id", ")", "{", "return", "$", "id", "===", "Unit", "::", "RELIC", "||", "$", "id", "===", "Unit", "::", "DEER", "||", "$", "id", "===", "Unit", "::", "BOAR", "||", "$", "id", "===", "Unit", "::", "JA...
Checks whether a unit type ID is a GAIA unit. Used to determine which units to draw on a map as not belonging to any player. @param int $id Unit type ID. @return bool True if the unit type is a GAIA unit, false otherwise.
[ "Checks", "whether", "a", "unit", "type", "ID", "is", "a", "GAIA", "unit", ".", "Used", "to", "determine", "which", "units", "to", "draw", "on", "a", "map", "as", "not", "belonging", "to", "any", "player", "." ]
daec4916d04a73cf89f9325ad77bfaf0644fda06
https://github.com/goto-bus-stop/recanalyst/blob/daec4916d04a73cf89f9325ad77bfaf0644fda06/src/ResourcePacks/AgeOfEmpires.php#L166-L174
train
goto-bus-stop/recanalyst
src/Model/GameInfo.php
GameInfo.getPOV
public function getPOV() { foreach ($this->owner->players as $player) { if ($player->owner) { return $player->name; } } return ''; }
php
public function getPOV() { foreach ($this->owner->players as $player) { if ($player->owner) { return $player->name; } } return ''; }
[ "public", "function", "getPOV", "(", ")", "{", "foreach", "(", "$", "this", "->", "owner", "->", "players", "as", "$", "player", ")", "{", "if", "(", "$", "player", "->", "owner", ")", "{", "return", "$", "player", "->", "name", ";", "}", "}", "r...
Returns the point of view. @return string
[ "Returns", "the", "point", "of", "view", "." ]
daec4916d04a73cf89f9325ad77bfaf0644fda06
https://github.com/goto-bus-stop/recanalyst/blob/daec4916d04a73cf89f9325ad77bfaf0644fda06/src/Model/GameInfo.php#L79-L87
train
goto-bus-stop/recanalyst
src/Model/GameInfo.php
GameInfo.ingameCoop
public function ingameCoop() { foreach ($this->owner->players as $player) { if ($player->isCooping) { return true; } } return false; }
php
public function ingameCoop() { foreach ($this->owner->players as $player) { if ($player->isCooping) { return true; } } return false; }
[ "public", "function", "ingameCoop", "(", ")", "{", "foreach", "(", "$", "this", "->", "owner", "->", "players", "as", "$", "player", ")", "{", "if", "(", "$", "player", "->", "isCooping", ")", "{", "return", "true", ";", "}", "}", "return", "false", ...
Determines if there is a cooping player in the game. @return bool True, if there is a cooping player in the game, false otherwise.
[ "Determines", "if", "there", "is", "a", "cooping", "player", "in", "the", "game", "." ]
daec4916d04a73cf89f9325ad77bfaf0644fda06
https://github.com/goto-bus-stop/recanalyst/blob/daec4916d04a73cf89f9325ad77bfaf0644fda06/src/Model/GameInfo.php#L127-L135
train
goto-bus-stop/recanalyst
examples/laravel.php
RecAnalystController.showMapImage
public function showMapImage(Request $request) { // The RecordedGame constructor accepts SplFileInfo instances, // so uploaded files can be passed straight to it: $rec = new RecordedGame($request->file('game')); // `mapImage()` returns an instance of \Intervention\Image, which has a // Laravel-compatible `response()` method. return $rec->mapImage()->response('png'); }
php
public function showMapImage(Request $request) { // The RecordedGame constructor accepts SplFileInfo instances, // so uploaded files can be passed straight to it: $rec = new RecordedGame($request->file('game')); // `mapImage()` returns an instance of \Intervention\Image, which has a // Laravel-compatible `response()` method. return $rec->mapImage()->response('png'); }
[ "public", "function", "showMapImage", "(", "Request", "$", "request", ")", "{", "// The RecordedGame constructor accepts SplFileInfo instances,", "// so uploaded files can be passed straight to it:", "$", "rec", "=", "new", "RecordedGame", "(", "$", "request", "->", "file", ...
Render a PNG map image and send it to the browser.
[ "Render", "a", "PNG", "map", "image", "and", "send", "it", "to", "the", "browser", "." ]
daec4916d04a73cf89f9325ad77bfaf0644fda06
https://github.com/goto-bus-stop/recanalyst/blob/daec4916d04a73cf89f9325ad77bfaf0644fda06/examples/laravel.php#L16-L25
train
goto-bus-stop/recanalyst
src/Model/Player.php
Player.team
public function team() { $teams = $this->rec->teams(); foreach ($teams as $team) { if ($team->index() === $this->teamIndex) { return $team; } } }
php
public function team() { $teams = $this->rec->teams(); foreach ($teams as $team) { if ($team->index() === $this->teamIndex) { return $team; } } }
[ "public", "function", "team", "(", ")", "{", "$", "teams", "=", "$", "this", "->", "rec", "->", "teams", "(", ")", ";", "foreach", "(", "$", "teams", "as", "$", "team", ")", "{", "if", "(", "$", "team", "->", "index", "(", ")", "===", "$", "t...
Get the player's team. @return \RecAnalyst\Model\Team|null
[ "Get", "the", "player", "s", "team", "." ]
daec4916d04a73cf89f9325ad77bfaf0644fda06
https://github.com/goto-bus-stop/recanalyst/blob/daec4916d04a73cf89f9325ad77bfaf0644fda06/src/Model/Player.php#L177-L185
train
goto-bus-stop/recanalyst
src/Model/Player.php
Player.color
public function color() { if (is_null($this->rec)) { return null; } $resourcePack = $this->rec->getResourcePack(); return $resourcePack->getPlayerColor($this->colorId); }
php
public function color() { if (is_null($this->rec)) { return null; } $resourcePack = $this->rec->getResourcePack(); return $resourcePack->getPlayerColor($this->colorId); }
[ "public", "function", "color", "(", ")", "{", "if", "(", "is_null", "(", "$", "this", "->", "rec", ")", ")", "{", "return", "null", ";", "}", "$", "resourcePack", "=", "$", "this", "->", "rec", "->", "getResourcePack", "(", ")", ";", "return", "$",...
Get the hex color of this player. @return string Hexadecimal representation of this player's color.
[ "Get", "the", "hex", "color", "of", "this", "player", "." ]
daec4916d04a73cf89f9325ad77bfaf0644fda06
https://github.com/goto-bus-stop/recanalyst/blob/daec4916d04a73cf89f9325ad77bfaf0644fda06/src/Model/Player.php#L263-L270
train
goto-bus-stop/recanalyst
src/Model/Player.php
Player.addResearch
public function addResearch($id, $time) { $this->researchesById[$id] = new Research($this->rec, $id, $time); }
php
public function addResearch($id, $time) { $this->researchesById[$id] = new Research($this->rec, $id, $time); }
[ "public", "function", "addResearch", "(", "$", "id", ",", "$", "time", ")", "{", "$", "this", "->", "researchesById", "[", "$", "id", "]", "=", "new", "Research", "(", "$", "this", "->", "rec", ",", "$", "id", ",", "$", "time", ")", ";", "}" ]
Add a research action. @param int $id Research ID. @param int $time Research completion time.
[ "Add", "a", "research", "action", "." ]
daec4916d04a73cf89f9325ad77bfaf0644fda06
https://github.com/goto-bus-stop/recanalyst/blob/daec4916d04a73cf89f9325ad77bfaf0644fda06/src/Model/Player.php#L293-L296
train
goto-bus-stop/recanalyst
src/Model/Player.php
Player.civName
public function civName() { if (!is_null($this->rec)) { return $this->rec->trans('civilizations', $this->civId); } return 'Civ #' . $this->civId; }
php
public function civName() { if (!is_null($this->rec)) { return $this->rec->trans('civilizations', $this->civId); } return 'Civ #' . $this->civId; }
[ "public", "function", "civName", "(", ")", "{", "if", "(", "!", "is_null", "(", "$", "this", "->", "rec", ")", ")", "{", "return", "$", "this", "->", "rec", "->", "trans", "(", "'civilizations'", ",", "$", "this", "->", "civId", ")", ";", "}", "r...
Get the name of this player's civilization. @return string
[ "Get", "the", "name", "of", "this", "player", "s", "civilization", "." ]
daec4916d04a73cf89f9325ad77bfaf0644fda06
https://github.com/goto-bus-stop/recanalyst/blob/daec4916d04a73cf89f9325ad77bfaf0644fda06/src/Model/Player.php#L311-L317
train
goto-bus-stop/recanalyst
src/Model/Player.php
Player.startingAge
public function startingAge() { if (!is_null($this->rec)) { return $this->rec->trans('ages', $this->initialState->startingAge); } return null; }
php
public function startingAge() { if (!is_null($this->rec)) { return $this->rec->trans('ages', $this->initialState->startingAge); } return null; }
[ "public", "function", "startingAge", "(", ")", "{", "if", "(", "!", "is_null", "(", "$", "this", "->", "rec", ")", ")", "{", "return", "$", "this", "->", "rec", "->", "trans", "(", "'ages'", ",", "$", "this", "->", "initialState", "->", "startingAge"...
Get the player's starting age. @see \RecAnalyst\Model\InitialState::$startingAge @return string Name of the starting age.
[ "Get", "the", "player", "s", "starting", "age", "." ]
daec4916d04a73cf89f9325ad77bfaf0644fda06
https://github.com/goto-bus-stop/recanalyst/blob/daec4916d04a73cf89f9325ad77bfaf0644fda06/src/Model/Player.php#L326-L332
train
goto-bus-stop/recanalyst
src/Analyzers/Analyzer.php
Analyzer.analyze
public function analyze(RecordedGame $game) { $this->rec = $game; $this->header = $game->getHeaderContents(); $this->body = $game->getBodyContents(); $this->headerSize = strlen($this->header); $this->bodySize = strlen($this->body); return $this->run(); }
php
public function analyze(RecordedGame $game) { $this->rec = $game; $this->header = $game->getHeaderContents(); $this->body = $game->getBodyContents(); $this->headerSize = strlen($this->header); $this->bodySize = strlen($this->body); return $this->run(); }
[ "public", "function", "analyze", "(", "RecordedGame", "$", "game", ")", "{", "$", "this", "->", "rec", "=", "$", "game", ";", "$", "this", "->", "header", "=", "$", "game", "->", "getHeaderContents", "(", ")", ";", "$", "this", "->", "body", "=", "...
Run this analysis on a recorded game. @param \RecAnalyst\RecordedGame $game Recorded game to analyze. @return mixed Result of the analysis.
[ "Run", "this", "analysis", "on", "a", "recorded", "game", "." ]
daec4916d04a73cf89f9325ad77bfaf0644fda06
https://github.com/goto-bus-stop/recanalyst/blob/daec4916d04a73cf89f9325ad77bfaf0644fda06/src/Analyzers/Analyzer.php#L32-L41
train
goto-bus-stop/recanalyst
src/Analyzers/Analyzer.php
Analyzer.get
protected function get($analyzer, $arg = null) { return $this->rec->getAnalysis($analyzer, $arg)->analysis; }
php
protected function get($analyzer, $arg = null) { return $this->rec->getAnalysis($analyzer, $arg)->analysis; }
[ "protected", "function", "get", "(", "$", "analyzer", ",", "$", "arg", "=", "null", ")", "{", "return", "$", "this", "->", "rec", "->", "getAnalysis", "(", "$", "analyzer", ",", "$", "arg", ")", "->", "analysis", ";", "}" ]
Get the result of another analyzer. @param string $analyzer Analyzer class name. @param mixed $arg Optional argument to the analyzer. @return mixed Result of the analyzer.
[ "Get", "the", "result", "of", "another", "analyzer", "." ]
daec4916d04a73cf89f9325ad77bfaf0644fda06
https://github.com/goto-bus-stop/recanalyst/blob/daec4916d04a73cf89f9325ad77bfaf0644fda06/src/Analyzers/Analyzer.php#L50-L53
train
goto-bus-stop/recanalyst
src/Analyzers/Analyzer.php
Analyzer.read
protected function read($analyzer, $arg = null) { $result = $this->rec->getAnalysis($analyzer, $arg, $this->position); $this->position = $result->position; return $result->analysis; }
php
protected function read($analyzer, $arg = null) { $result = $this->rec->getAnalysis($analyzer, $arg, $this->position); $this->position = $result->position; return $result->analysis; }
[ "protected", "function", "read", "(", "$", "analyzer", ",", "$", "arg", "=", "null", ")", "{", "$", "result", "=", "$", "this", "->", "rec", "->", "getAnalysis", "(", "$", "analyzer", ",", "$", "arg", ",", "$", "this", "->", "position", ")", ";", ...
Compose another analyzer. Starts reading at the current position, and uses the composed analyzer's final position as the new position. @param string $analyzer Analyzer class name. @param mixed $arg Optional argument to the analyzer. @return mixed Result of the analyzer.
[ "Compose", "another", "analyzer", ".", "Starts", "reading", "at", "the", "current", "position", "and", "uses", "the", "composed", "analyzer", "s", "final", "position", "as", "the", "new", "position", "." ]
daec4916d04a73cf89f9325ad77bfaf0644fda06
https://github.com/goto-bus-stop/recanalyst/blob/daec4916d04a73cf89f9325ad77bfaf0644fda06/src/Analyzers/Analyzer.php#L63-L68
train
goto-bus-stop/recanalyst
src/Analyzers/Analyzer.php
Analyzer.readHeader
protected function readHeader($type, $size) { if ($this->position + $size > $this->headerSize) { throw new \Exception('Can\'t read ' . $size . ' bytes'); } $data = unpack($type, substr($this->header, $this->position, $size)); $this->position += $size; return $data[1]; }
php
protected function readHeader($type, $size) { if ($this->position + $size > $this->headerSize) { throw new \Exception('Can\'t read ' . $size . ' bytes'); } $data = unpack($type, substr($this->header, $this->position, $size)); $this->position += $size; return $data[1]; }
[ "protected", "function", "readHeader", "(", "$", "type", ",", "$", "size", ")", "{", "if", "(", "$", "this", "->", "position", "+", "$", "size", ">", "$", "this", "->", "headerSize", ")", "{", "throw", "new", "\\", "Exception", "(", "'Can\\'t read '", ...
Read and unpack data from the header of the recorded game file. @see https://secure.php.net/pack For documentation on data unpack format. @param string $type Data type. @param int $size Size of the data. @return mixed Result.
[ "Read", "and", "unpack", "data", "from", "the", "header", "of", "the", "recorded", "game", "file", "." ]
daec4916d04a73cf89f9325ad77bfaf0644fda06
https://github.com/goto-bus-stop/recanalyst/blob/daec4916d04a73cf89f9325ad77bfaf0644fda06/src/Analyzers/Analyzer.php#L78-L86
train
goto-bus-stop/recanalyst
src/Analyzers/Analyzer.php
Analyzer.readHeaderRaw
protected function readHeaderRaw($size) { if ($this->position + $size > $this->headerSize) { throw new \Exception('Can\'t read ' . $size . ' bytes'); } $data = substr($this->header, $this->position, $size); $this->position += $size; return $data; }
php
protected function readHeaderRaw($size) { if ($this->position + $size > $this->headerSize) { throw new \Exception('Can\'t read ' . $size . ' bytes'); } $data = substr($this->header, $this->position, $size); $this->position += $size; return $data; }
[ "protected", "function", "readHeaderRaw", "(", "$", "size", ")", "{", "if", "(", "$", "this", "->", "position", "+", "$", "size", ">", "$", "this", "->", "headerSize", ")", "{", "throw", "new", "\\", "Exception", "(", "'Can\\'t read '", ".", "$", "size...
Read raw strings from the header of the recorded game file. @param int $size Amount of characters to read. @return string Result.
[ "Read", "raw", "strings", "from", "the", "header", "of", "the", "recorded", "game", "file", "." ]
daec4916d04a73cf89f9325ad77bfaf0644fda06
https://github.com/goto-bus-stop/recanalyst/blob/daec4916d04a73cf89f9325ad77bfaf0644fda06/src/Analyzers/Analyzer.php#L94-L102
train
goto-bus-stop/recanalyst
src/Analyzers/Analyzer.php
Analyzer.readBody
protected function readBody($type, $size) { $data = unpack($type, substr($this->body, $this->position, $size)); $this->position += $size; return $data[1]; }
php
protected function readBody($type, $size) { $data = unpack($type, substr($this->body, $this->position, $size)); $this->position += $size; return $data[1]; }
[ "protected", "function", "readBody", "(", "$", "type", ",", "$", "size", ")", "{", "$", "data", "=", "unpack", "(", "$", "type", ",", "substr", "(", "$", "this", "->", "body", ",", "$", "this", "->", "position", ",", "$", "size", ")", ")", ";", ...
Read and unpack data from the body of the recorded game file. @see https://secure.php.net/pack For documentation on data unpack format. @param string $type Data type. @param int $size Size of the data. @return mixed Result.
[ "Read", "and", "unpack", "data", "from", "the", "body", "of", "the", "recorded", "game", "file", "." ]
daec4916d04a73cf89f9325ad77bfaf0644fda06
https://github.com/goto-bus-stop/recanalyst/blob/daec4916d04a73cf89f9325ad77bfaf0644fda06/src/Analyzers/Analyzer.php#L112-L117
train
goto-bus-stop/recanalyst
src/Analyzers/Analyzer.php
Analyzer.readBodyRaw
protected function readBodyRaw($size) { $data = substr($this->body, $this->position, $size); $this->position += $size; return $data; }
php
protected function readBodyRaw($size) { $data = substr($this->body, $this->position, $size); $this->position += $size; return $data; }
[ "protected", "function", "readBodyRaw", "(", "$", "size", ")", "{", "$", "data", "=", "substr", "(", "$", "this", "->", "body", ",", "$", "this", "->", "position", ",", "$", "size", ")", ";", "$", "this", "->", "position", "+=", "$", "size", ";", ...
Read raw strings from the body of the recorded game file. @param int $size Amount of characters to read. @return string Result.
[ "Read", "raw", "strings", "from", "the", "body", "of", "the", "recorded", "game", "file", "." ]
daec4916d04a73cf89f9325ad77bfaf0644fda06
https://github.com/goto-bus-stop/recanalyst/blob/daec4916d04a73cf89f9325ad77bfaf0644fda06/src/Analyzers/Analyzer.php#L125-L130
train
digiaonline/lumen-elasticsearch
src/ElasticsearchServiceProvider.php
ElasticsearchServiceProvider.registerBindings
protected function registerBindings() { /** @noinspection PhpUndefinedMethodInspection */ $config = $this->app['config']->get('elasticsearch', []); $this->app->/** @scrutinizer ignore-call */ singleton(ElasticsearchServiceContract::class, function () use ($config) { return new ElasticsearchService(ClientBuilder::fromConfig($config)); }); }
php
protected function registerBindings() { /** @noinspection PhpUndefinedMethodInspection */ $config = $this->app['config']->get('elasticsearch', []); $this->app->/** @scrutinizer ignore-call */ singleton(ElasticsearchServiceContract::class, function () use ($config) { return new ElasticsearchService(ClientBuilder::fromConfig($config)); }); }
[ "protected", "function", "registerBindings", "(", ")", "{", "/** @noinspection PhpUndefinedMethodInspection */", "$", "config", "=", "$", "this", "->", "app", "[", "'config'", "]", "->", "get", "(", "'elasticsearch'", ",", "[", "]", ")", ";", "$", "this", "->"...
Register bindings.
[ "Register", "bindings", "." ]
45a2729afe131842b6ff70a8415aa829068075bd
https://github.com/digiaonline/lumen-elasticsearch/blob/45a2729afe131842b6ff70a8415aa829068075bd/src/ElasticsearchServiceProvider.php#L27-L35
train
digiaonline/lumen-elasticsearch
src/Pipelines/Stages/ReIndexStage.php
ReIndexStage.renderProgressBar
protected function renderProgressBar(array $task): void { // Use a progress bar to indicate how far a long the re-indexing has come $progressBar = null; do { $response = ['completed' => false]; // Ignore ServerErrorResponseException, re-indexing can make these requests time out try { $response = $this->elasticsearchService->tasks()->get([ 'task_id' => $task['task'], ]); $total = $response['task']['status']['total']; // Initialize the progress bar once Elasticsearch knows the total amount of items if ($progressBar === null && $total > 0) { $progressBar = new ProgressBar(new ConsoleOutput(), $total); } elseif ($progressBar !== null) { $progressBar->setProgress($response['task']['status']['created']); } } catch (ServerErrorResponseException $e) { } sleep(1); } while ((bool)$response['completed'] === false); // For very short migrations we may never get a progress bar, because the task finishes too quickly if ($progressBar !== null) { $progressBar->finish(); } echo PHP_EOL; }
php
protected function renderProgressBar(array $task): void { // Use a progress bar to indicate how far a long the re-indexing has come $progressBar = null; do { $response = ['completed' => false]; // Ignore ServerErrorResponseException, re-indexing can make these requests time out try { $response = $this->elasticsearchService->tasks()->get([ 'task_id' => $task['task'], ]); $total = $response['task']['status']['total']; // Initialize the progress bar once Elasticsearch knows the total amount of items if ($progressBar === null && $total > 0) { $progressBar = new ProgressBar(new ConsoleOutput(), $total); } elseif ($progressBar !== null) { $progressBar->setProgress($response['task']['status']['created']); } } catch (ServerErrorResponseException $e) { } sleep(1); } while ((bool)$response['completed'] === false); // For very short migrations we may never get a progress bar, because the task finishes too quickly if ($progressBar !== null) { $progressBar->finish(); } echo PHP_EOL; }
[ "protected", "function", "renderProgressBar", "(", "array", "$", "task", ")", ":", "void", "{", "// Use a progress bar to indicate how far a long the re-indexing has come", "$", "progressBar", "=", "null", ";", "do", "{", "$", "response", "=", "[", "'completed'", "=>"...
Renders a progress bar until the specified re-indexing task is completed @param array $task
[ "Renders", "a", "progress", "bar", "until", "the", "specified", "re", "-", "indexing", "task", "is", "completed" ]
45a2729afe131842b6ff70a8415aa829068075bd
https://github.com/digiaonline/lumen-elasticsearch/blob/45a2729afe131842b6ff70a8415aa829068075bd/src/Pipelines/Stages/ReIndexStage.php#L74-L108
train
inouet/file-cache
src/FileCache.php
FileCache.getDirectory
protected function getDirectory($id) { $hash = sha1($id, false); $dirs = array( $this->getCacheDirectory(), substr($hash, 0, 2), substr($hash, 2, 2) ); return join(DIRECTORY_SEPARATOR, $dirs); }
php
protected function getDirectory($id) { $hash = sha1($id, false); $dirs = array( $this->getCacheDirectory(), substr($hash, 0, 2), substr($hash, 2, 2) ); return join(DIRECTORY_SEPARATOR, $dirs); }
[ "protected", "function", "getDirectory", "(", "$", "id", ")", "{", "$", "hash", "=", "sha1", "(", "$", "id", ",", "false", ")", ";", "$", "dirs", "=", "array", "(", "$", "this", "->", "getCacheDirectory", "(", ")", ",", "substr", "(", "$", "hash", ...
Fetches a directory to store the cache data @param string $id @return string
[ "Fetches", "a", "directory", "to", "store", "the", "cache", "data" ]
cb11041657925c95c358ca0bf70bd401a671efa3
https://github.com/inouet/file-cache/blob/cb11041657925c95c358ca0bf70bd401a671efa3/src/FileCache.php#L117-L126
train
inouet/file-cache
src/FileCache.php
FileCache.getFileName
protected function getFileName($id) { $directory = $this->getDirectory($id); $hash = sha1($id, false); $file = $directory . DIRECTORY_SEPARATOR . $hash . '.cache'; return $file; }
php
protected function getFileName($id) { $directory = $this->getDirectory($id); $hash = sha1($id, false); $file = $directory . DIRECTORY_SEPARATOR . $hash . '.cache'; return $file; }
[ "protected", "function", "getFileName", "(", "$", "id", ")", "{", "$", "directory", "=", "$", "this", "->", "getDirectory", "(", "$", "id", ")", ";", "$", "hash", "=", "sha1", "(", "$", "id", ",", "false", ")", ";", "$", "file", "=", "$", "direct...
Fetches a file path of the cache data @param string $id @return string
[ "Fetches", "a", "file", "path", "of", "the", "cache", "data" ]
cb11041657925c95c358ca0bf70bd401a671efa3
https://github.com/inouet/file-cache/blob/cb11041657925c95c358ca0bf70bd401a671efa3/src/FileCache.php#L145-L151
train
denissimon/prediction-builder
src/PredictionBuilder.php
readData.readFromArray
public function readFromArray(array $data) { $callback = function ($v) { if ((!isset($v[0])) || (!isset($v[1]))) { throw new \InvalidArgumentException('Mismatch in the number of x and y in the dataset.'); } else { $this->xVector[] = $v[0]; $this->yVector[] = $v[1]; } }; array_walk($data, $callback); }
php
public function readFromArray(array $data) { $callback = function ($v) { if ((!isset($v[0])) || (!isset($v[1]))) { throw new \InvalidArgumentException('Mismatch in the number of x and y in the dataset.'); } else { $this->xVector[] = $v[0]; $this->yVector[] = $v[1]; } }; array_walk($data, $callback); }
[ "public", "function", "readFromArray", "(", "array", "$", "data", ")", "{", "$", "callback", "=", "function", "(", "$", "v", ")", "{", "if", "(", "(", "!", "isset", "(", "$", "v", "[", "0", "]", ")", ")", "||", "(", "!", "isset", "(", "$", "v...
Reads the data from a given array @param array $data @throws \InvalidArgumentException
[ "Reads", "the", "data", "from", "a", "given", "array" ]
fe02c342ec59861c49d075836f351250fb7163a7
https://github.com/denissimon/prediction-builder/blob/fe02c342ec59861c49d075836f351250fb7163a7/src/PredictionBuilder.php#L21-L32
train
denissimon/prediction-builder
src/PredictionBuilder.php
PredictionBuilder.sumSquared
private function sumSquared(array $vector) { return array_reduce( $vector, function($v, $w) { return $v += $this->square($w); } ); }
php
private function sumSquared(array $vector) { return array_reduce( $vector, function($v, $w) { return $v += $this->square($w); } ); }
[ "private", "function", "sumSquared", "(", "array", "$", "vector", ")", "{", "return", "array_reduce", "(", "$", "vector", ",", "function", "(", "$", "v", ",", "$", "w", ")", "{", "return", "$", "v", "+=", "$", "this", "->", "square", "(", "$", "w",...
Sum of the vector squared values @param array $vector @return number
[ "Sum", "of", "the", "vector", "squared", "values" ]
fe02c342ec59861c49d075836f351250fb7163a7
https://github.com/denissimon/prediction-builder/blob/fe02c342ec59861c49d075836f351250fb7163a7/src/PredictionBuilder.php#L103-L108
train
denissimon/prediction-builder
src/PredictionBuilder.php
PredictionBuilder.build
public function build() { // Check the number of observations in a given dataset if ($this->count < 3) { throw new \InvalidArgumentException('The dataset should contain a minimum of 3 observations.'); } $b = $this->round_($this->bSlope()); $a = $this->round_($this->aIntercept($b)); $model = $this->createModel($a, $b); $y = $this->round_($model($this->x)); $result = new \stdClass(); $result->ln_model = (string) ($a.'+'.$b.'x'); $result->cor = $this->round_($this->corCoefficient($b)); $result->x = $this->x; $result->y = $y; return $result; }
php
public function build() { // Check the number of observations in a given dataset if ($this->count < 3) { throw new \InvalidArgumentException('The dataset should contain a minimum of 3 observations.'); } $b = $this->round_($this->bSlope()); $a = $this->round_($this->aIntercept($b)); $model = $this->createModel($a, $b); $y = $this->round_($model($this->x)); $result = new \stdClass(); $result->ln_model = (string) ($a.'+'.$b.'x'); $result->cor = $this->round_($this->corCoefficient($b)); $result->x = $this->x; $result->y = $y; return $result; }
[ "public", "function", "build", "(", ")", "{", "// Check the number of observations in a given dataset", "if", "(", "$", "this", "->", "count", "<", "3", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'The dataset should contain a minimum of 3 observatio...
Builds a prediction of the expected value of y for a given x, based on a linear regression model. @return \stdClass @throws \InvalidArgumentException
[ "Builds", "a", "prediction", "of", "the", "expected", "value", "of", "y", "for", "a", "given", "x", "based", "on", "a", "linear", "regression", "model", "." ]
fe02c342ec59861c49d075836f351250fb7163a7
https://github.com/denissimon/prediction-builder/blob/fe02c342ec59861c49d075836f351250fb7163a7/src/PredictionBuilder.php#L206-L224
train
davestewart/laravel-sketchpad
src/help/docs/HelpersController.php
HelpersController.code
public function code($arguments = 'php') { $params = [ 'php' => [ 'desc' => 'raw PHP', 'func' => 'output', 'args' => ['$a + $b === 100 ? true : false'] ], 'js' => [ 'desc' => 'raw JavaScript', 'func' => 'output', 'args' => ['a + b === 100 ? true : false', 'javascript'] ], 'file' => [ 'desc' => 'this file', 'func' => 'file', 'args' => [__FILE__] ], 'section' => [ 'desc' => 'lines 17 - 44 of this file', 'func' => 'section', 'args' => [__FILE__, 18, 45] ], 'sectionu' => [ 'desc' => 'lines 17 - 44 of this file (without indent)', 'func' => 'section', 'args' => [__FILE__, 18, 45, true] ], 'class' => [ 'desc' => 'this class', 'func' => 'classfile', 'args' => [__CLASS__] ], 'classc' => [ 'desc' => 'this class (with doc-comment)', 'func' => 'classfile', 'args' => [__CLASS__, true] ], 'method' => [ 'desc' => 'this method', 'func' => 'method', 'args' => [__CLASS__, 'code'] ], 'methodc' => [ 'desc' => 'this method (with doc-comment)', 'func' => 'method', 'args' => [__CLASS__, 'code', true] ], ]; $data = $params[$arguments]; $data['signature'] = Code::signature($data['args']); return view('sketchpad::help/helpers/code', $data); }
php
public function code($arguments = 'php') { $params = [ 'php' => [ 'desc' => 'raw PHP', 'func' => 'output', 'args' => ['$a + $b === 100 ? true : false'] ], 'js' => [ 'desc' => 'raw JavaScript', 'func' => 'output', 'args' => ['a + b === 100 ? true : false', 'javascript'] ], 'file' => [ 'desc' => 'this file', 'func' => 'file', 'args' => [__FILE__] ], 'section' => [ 'desc' => 'lines 17 - 44 of this file', 'func' => 'section', 'args' => [__FILE__, 18, 45] ], 'sectionu' => [ 'desc' => 'lines 17 - 44 of this file (without indent)', 'func' => 'section', 'args' => [__FILE__, 18, 45, true] ], 'class' => [ 'desc' => 'this class', 'func' => 'classfile', 'args' => [__CLASS__] ], 'classc' => [ 'desc' => 'this class (with doc-comment)', 'func' => 'classfile', 'args' => [__CLASS__, true] ], 'method' => [ 'desc' => 'this method', 'func' => 'method', 'args' => [__CLASS__, 'code'] ], 'methodc' => [ 'desc' => 'this method (with doc-comment)', 'func' => 'method', 'args' => [__CLASS__, 'code', true] ], ]; $data = $params[$arguments]; $data['signature'] = Code::signature($data['args']); return view('sketchpad::help/helpers/code', $data); }
[ "public", "function", "code", "(", "$", "arguments", "=", "'php'", ")", "{", "$", "params", "=", "[", "'php'", "=>", "[", "'desc'", "=>", "'raw PHP'", ",", "'func'", "=>", "'output'", ",", "'args'", "=>", "[", "'$a + $b === 100 ? true : false'", "]", "]", ...
Output code with formatting and html entities converted @field select $arguments options:Raw PHP=php,Raw JavaScript=js,File=file,Section=section,Section (without indent)=sectionu,Class=class,Class (with doc-comment)=classc,Method=method,Method (with doc-comment)=methodc
[ "Output", "code", "with", "formatting", "and", "html", "entities", "converted" ]
ebd3365265f8844f7d400d7d530605512a20011c
https://github.com/davestewart/laravel-sketchpad/blob/ebd3365265f8844f7d400d7d530605512a20011c/src/help/docs/HelpersController.php#L65-L118
train
davestewart/laravel-sketchpad
src/help/docs/HelpersController.php
HelpersController.icon
public function icon() { $input = [ [icon('plane'), "icon('plane');", ], [icon('bolt'), "icon('bolt');", ], [icon('bolt', '#FF00FF'), "icon('bolt', '#FF00FF');", ], [icon('info', 'info'), "icon('info', 'info');", ], [icon(true), "icon(true);", ], [icon(false), "icon(false);", ], ]; $data = array_reduce($input, function ($output, $arr) { $output[] = (object) ['code' => $arr[1], 'icon' => $arr[0]]; return $output; }, []); return view('sketchpad::help/helpers/icon', compact('data')); }
php
public function icon() { $input = [ [icon('plane'), "icon('plane');", ], [icon('bolt'), "icon('bolt');", ], [icon('bolt', '#FF00FF'), "icon('bolt', '#FF00FF');", ], [icon('info', 'info'), "icon('info', 'info');", ], [icon(true), "icon(true);", ], [icon(false), "icon(false);", ], ]; $data = array_reduce($input, function ($output, $arr) { $output[] = (object) ['code' => $arr[1], 'icon' => $arr[0]]; return $output; }, []); return view('sketchpad::help/helpers/icon', compact('data')); }
[ "public", "function", "icon", "(", ")", "{", "$", "input", "=", "[", "[", "icon", "(", "'plane'", ")", ",", "\"icon('plane');\"", ",", "]", ",", "[", "icon", "(", "'bolt'", ")", ",", "\"icon('bolt');\"", ",", "]", ",", "[", "icon", "(", "'bolt'", "...
Create a Font Awesome icon simply and easily
[ "Create", "a", "Font", "Awesome", "icon", "simply", "and", "easily" ]
ebd3365265f8844f7d400d7d530605512a20011c
https://github.com/davestewart/laravel-sketchpad/blob/ebd3365265f8844f7d400d7d530605512a20011c/src/help/docs/HelpersController.php#L149-L165
train
davestewart/laravel-sketchpad
src/controllers/ApiController.php
ApiController.run
public function run(Request $request, $path = '') { // data $data = $request->get('_data', []); if (is_string($data)) { $data = json_decode($data, JSON_OBJECT_AS_ARRAY); } // form $form = $request->get('_form', null); parse_str($form, $form); // run return $this->sketchpad->run($path, $data, $form); }
php
public function run(Request $request, $path = '') { // data $data = $request->get('_data', []); if (is_string($data)) { $data = json_decode($data, JSON_OBJECT_AS_ARRAY); } // form $form = $request->get('_form', null); parse_str($form, $form); // run return $this->sketchpad->run($path, $data, $form); }
[ "public", "function", "run", "(", "Request", "$", "request", ",", "$", "path", "=", "''", ")", "{", "// data", "$", "data", "=", "$", "request", "->", "get", "(", "'_data'", ",", "[", "]", ")", ";", "if", "(", "is_string", "(", "$", "data", ")", ...
Run a controller method @param Request $request @param string $path @return \Illuminate\View\View|mixed|string
[ "Run", "a", "controller", "method" ]
ebd3365265f8844f7d400d7d530605512a20011c
https://github.com/davestewart/laravel-sketchpad/blob/ebd3365265f8844f7d400d7d530605512a20011c/src/controllers/ApiController.php#L54-L69
train
davestewart/laravel-sketchpad
src/controllers/ApiController.php
ApiController.settings
public function settings(Request $request, SketchpadConfig $config) { if (!$config->admin->settings) { return response()->json($config->settings); } function textToArray ($text) { return array_values(array_filter(array_map('trim', explode("\n", trim($text))), 'strlen')); } if($request->isMethod('post')) { // convert data $data = json_decode($request->get('settings')); // trim values $data->livereload->paths = textToArray($data->livereload->paths); // save $config->settings->save((array) $data); } return response()->json($config->settings); }
php
public function settings(Request $request, SketchpadConfig $config) { if (!$config->admin->settings) { return response()->json($config->settings); } function textToArray ($text) { return array_values(array_filter(array_map('trim', explode("\n", trim($text))), 'strlen')); } if($request->isMethod('post')) { // convert data $data = json_decode($request->get('settings')); // trim values $data->livereload->paths = textToArray($data->livereload->paths); // save $config->settings->save((array) $data); } return response()->json($config->settings); }
[ "public", "function", "settings", "(", "Request", "$", "request", ",", "SketchpadConfig", "$", "config", ")", "{", "if", "(", "!", "$", "config", "->", "admin", "->", "settings", ")", "{", "return", "response", "(", ")", "->", "json", "(", "$", "config...
Loads or saves settings data @method POST @method GET @param Request $request @param SketchpadConfig $config @return SketchpadSettings
[ "Loads", "or", "saves", "settings", "data" ]
ebd3365265f8844f7d400d7d530605512a20011c
https://github.com/davestewart/laravel-sketchpad/blob/ebd3365265f8844f7d400d7d530605512a20011c/src/controllers/ApiController.php#L104-L128
train
davestewart/laravel-sketchpad
src/controllers/ApiController.php
ApiController.path
public function path(Request $request) { $relpath = $request->get('path'); $abspath = base_path($relpath); return [ 'relpath' => $relpath, 'abspath' => $abspath, 'exists' => file_exists($abspath) ]; }
php
public function path(Request $request) { $relpath = $request->get('path'); $abspath = base_path($relpath); return [ 'relpath' => $relpath, 'abspath' => $abspath, 'exists' => file_exists($abspath) ]; }
[ "public", "function", "path", "(", "Request", "$", "request", ")", "{", "$", "relpath", "=", "$", "request", "->", "get", "(", "'path'", ")", ";", "$", "abspath", "=", "base_path", "(", "$", "relpath", ")", ";", "return", "[", "'relpath'", "=>", "$",...
Validates existence of a path @method GET @param Request $request @return array
[ "Validates", "existence", "of", "a", "path" ]
ebd3365265f8844f7d400d7d530605512a20011c
https://github.com/davestewart/laravel-sketchpad/blob/ebd3365265f8844f7d400d7d530605512a20011c/src/controllers/ApiController.php#L137-L146
train
esbenp/onion
src/Onion.php
Onion.peel
public function peel($object, Closure $core) { $coreFunction = $this->createCoreFunction($core); // Since we will be "currying" the functions starting with the first // in the array, the first function will be "closer" to the core. // This also means it will be run last. However, if the reverse the // order of the array, the first in the list will be the outer layers. $layers = array_reverse($this->layers); // We create the onion by starting initially with the core and then // gradually wrap it in layers. Each layer will have the next layer "curried" // into it and will have the current state (the object) passed to it. $completeOnion = array_reduce($layers, function($nextLayer, $layer){ return $this->createLayer($nextLayer, $layer); }, $coreFunction); // We now have the complete onion and can start passing the object // down through the layers. return $completeOnion($object); }
php
public function peel($object, Closure $core) { $coreFunction = $this->createCoreFunction($core); // Since we will be "currying" the functions starting with the first // in the array, the first function will be "closer" to the core. // This also means it will be run last. However, if the reverse the // order of the array, the first in the list will be the outer layers. $layers = array_reverse($this->layers); // We create the onion by starting initially with the core and then // gradually wrap it in layers. Each layer will have the next layer "curried" // into it and will have the current state (the object) passed to it. $completeOnion = array_reduce($layers, function($nextLayer, $layer){ return $this->createLayer($nextLayer, $layer); }, $coreFunction); // We now have the complete onion and can start passing the object // down through the layers. return $completeOnion($object); }
[ "public", "function", "peel", "(", "$", "object", ",", "Closure", "$", "core", ")", "{", "$", "coreFunction", "=", "$", "this", "->", "createCoreFunction", "(", "$", "core", ")", ";", "// Since we will be \"currying\" the functions starting with the first", "// in t...
Run middleware around core function and pass an object through it @param mixed $object @param Closure $core @return mixed
[ "Run", "middleware", "around", "core", "function", "and", "pass", "an", "object", "through", "it" ]
71014ae0727c289213f54c867933665342345d91
https://github.com/esbenp/onion/blob/71014ae0727c289213f54c867933665342345d91/src/Onion.php#L47-L67
train
esbenp/onion
src/Onion.php
Onion.createLayer
private function createLayer($nextLayer, $layer) { return function($object) use($nextLayer, $layer){ return $layer->peel($object, $nextLayer); }; }
php
private function createLayer($nextLayer, $layer) { return function($object) use($nextLayer, $layer){ return $layer->peel($object, $nextLayer); }; }
[ "private", "function", "createLayer", "(", "$", "nextLayer", ",", "$", "layer", ")", "{", "return", "function", "(", "$", "object", ")", "use", "(", "$", "nextLayer", ",", "$", "layer", ")", "{", "return", "$", "layer", "->", "peel", "(", "$", "objec...
Get an onion layer function. This function will get the object from a previous layer and pass it inwards @param LayerInterface $nextLayer @param LayerInterface $layer @return Closure
[ "Get", "an", "onion", "layer", "function", ".", "This", "function", "will", "get", "the", "object", "from", "a", "previous", "layer", "and", "pass", "it", "inwards" ]
71014ae0727c289213f54c867933665342345d91
https://github.com/esbenp/onion/blob/71014ae0727c289213f54c867933665342345d91/src/Onion.php#L98-L103
train
davestewart/laravel-sketchpad
src/services/Sketchpad.php
Sketchpad.getController
public function getController($route = null) { $router = $this->init($route == null)->router; return $route ? $router->getController($route) : $router->getControllers(); }
php
public function getController($route = null) { $router = $this->init($route == null)->router; return $route ? $router->getController($route) : $router->getControllers(); }
[ "public", "function", "getController", "(", "$", "route", "=", "null", ")", "{", "$", "router", "=", "$", "this", "->", "init", "(", "$", "route", "==", "null", ")", "->", "router", ";", "return", "$", "route", "?", "$", "router", "->", "getControlle...
Returns a sketchpad\objects\reflection\Controller that can be converted to JSON @param string $route The relative route to the controller @return Controller The Controller
[ "Returns", "a", "sketchpad", "\\", "objects", "\\", "reflection", "\\", "Controller", "that", "can", "be", "converted", "to", "JSON" ]
ebd3365265f8844f7d400d7d530605512a20011c
https://github.com/davestewart/laravel-sketchpad/blob/ebd3365265f8844f7d400d7d530605512a20011c/src/services/Sketchpad.php#L99-L105
train
davestewart/laravel-sketchpad
src/services/Sketchpad.php
Sketchpad.run
public function run($route = '', array $params, array $form = null) { // set up the router, but don't scan $this->init(); /** @var CallReference $ref */ $ref = $this->router->getCall($route, $params); //vd([$ref, $route, $params]); //exit; // controller has method if($ref instanceof CallReference) { // test controller / method exists try { new ReflectionMethod($ref->class, $ref->method); } catch(\Exception $e) { if($e instanceof \ReflectionException) { //$sketchpad = str_replace($this->config->route, '', $ref->route) . $ref->method . '/'; $this->abort($ref->route . '::' . $ref->method . '()', 'method'); } } // assign static properties Sketchpad::$route = $ref->route . '/' . $ref->method . '/'; Sketchpad::$params = $ref->params; Sketchpad::$form = empty($form) ? null : $form; // get controller response or content ob_start(); $response = $this->exec($ref->class, $ref->method, $ref->params); $content = ob_get_contents(); ob_end_clean(); // handle echoed output if ($content) { return $content; } // handle laravel view responses if ($response instanceof \Illuminate\Contracts\View\View) { return $response; } // handle laravel json responses if ($response instanceof \Illuminate\Http\JsonResponse) { return json($response->getData()); } // handle Arrrayable if ($response instanceof \Illuminate\Contracts\Support\Arrayable) { return json($response->toArray()); } // handle Jsonable if ($response instanceof \Illuminate\Contracts\Support\Jsonable) { return json(json_decode($response->toJson())); } // anything else send as JSON (classes, objects, arrays, numbers, strings, booleans) return json($response); } // if there's not a valid controller or method, it's a 404 $this->abort($route, 'path'); return false; }
php
public function run($route = '', array $params, array $form = null) { // set up the router, but don't scan $this->init(); /** @var CallReference $ref */ $ref = $this->router->getCall($route, $params); //vd([$ref, $route, $params]); //exit; // controller has method if($ref instanceof CallReference) { // test controller / method exists try { new ReflectionMethod($ref->class, $ref->method); } catch(\Exception $e) { if($e instanceof \ReflectionException) { //$sketchpad = str_replace($this->config->route, '', $ref->route) . $ref->method . '/'; $this->abort($ref->route . '::' . $ref->method . '()', 'method'); } } // assign static properties Sketchpad::$route = $ref->route . '/' . $ref->method . '/'; Sketchpad::$params = $ref->params; Sketchpad::$form = empty($form) ? null : $form; // get controller response or content ob_start(); $response = $this->exec($ref->class, $ref->method, $ref->params); $content = ob_get_contents(); ob_end_clean(); // handle echoed output if ($content) { return $content; } // handle laravel view responses if ($response instanceof \Illuminate\Contracts\View\View) { return $response; } // handle laravel json responses if ($response instanceof \Illuminate\Http\JsonResponse) { return json($response->getData()); } // handle Arrrayable if ($response instanceof \Illuminate\Contracts\Support\Arrayable) { return json($response->toArray()); } // handle Jsonable if ($response instanceof \Illuminate\Contracts\Support\Jsonable) { return json(json_decode($response->toJson())); } // anything else send as JSON (classes, objects, arrays, numbers, strings, booleans) return json($response); } // if there's not a valid controller or method, it's a 404 $this->abort($route, 'path'); return false; }
[ "public", "function", "run", "(", "$", "route", "=", "''", ",", "array", "$", "params", ",", "array", "$", "form", "=", "null", ")", "{", "// set up the router, but don't scan", "$", "this", "->", "init", "(", ")", ";", "/** @var CallReference $ref */", "$",...
Initial function that works out the controller, method and parameters to call from the URI string @param string $route @param array $params @param array $form @return mixed|string
[ "Initial", "function", "that", "works", "out", "the", "controller", "method", "and", "parameters", "to", "call", "from", "the", "URI", "string" ]
ebd3365265f8844f7d400d7d530605512a20011c
https://github.com/davestewart/laravel-sketchpad/blob/ebd3365265f8844f7d400d7d530605512a20011c/src/services/Sketchpad.php#L119-L195
train
davestewart/laravel-sketchpad
src/services/Sketchpad.php
Sketchpad.exec
public function exec($controller, $method, $params = null) { $callable = "$controller@$method"; return $params ? App::call($callable, $this->getCallParams($controller, $method, $params)) : App::call($callable); }
php
public function exec($controller, $method, $params = null) { $callable = "$controller@$method"; return $params ? App::call($callable, $this->getCallParams($controller, $method, $params)) : App::call($callable); }
[ "public", "function", "exec", "(", "$", "controller", ",", "$", "method", ",", "$", "params", "=", "null", ")", "{", "$", "callable", "=", "\"$controller@$method\"", ";", "return", "$", "params", "?", "App", "::", "call", "(", "$", "callable", ",", "$"...
Calls a controller and methods, resolving any dependency injection @param string $controller The FQ name of the controller @param string $method The name of the method @param array|null $params An optional array of parameters @return mixed The result of the call
[ "Calls", "a", "controller", "and", "methods", "resolving", "any", "dependency", "injection" ]
ebd3365265f8844f7d400d7d530605512a20011c
https://github.com/davestewart/laravel-sketchpad/blob/ebd3365265f8844f7d400d7d530605512a20011c/src/services/Sketchpad.php#L209-L215
train
davestewart/laravel-sketchpad
src/traits/SaveFileTrait.php
SaveFileTrait._save
protected function _save($file, $data) { // variables $folder = dirname($file); // ensure folder exists if(!file_exists($folder)) { mkdir($folder, 0777, true); } // ensure folder is writable else if(!is_writable($folder)) { chmod($folder, 0777); } // write file if (file_exists($file) && !is_writable($file)) { chmod($file, 0644); } file_put_contents($file, $data); }
php
protected function _save($file, $data) { // variables $folder = dirname($file); // ensure folder exists if(!file_exists($folder)) { mkdir($folder, 0777, true); } // ensure folder is writable else if(!is_writable($folder)) { chmod($folder, 0777); } // write file if (file_exists($file) && !is_writable($file)) { chmod($file, 0644); } file_put_contents($file, $data); }
[ "protected", "function", "_save", "(", "$", "file", ",", "$", "data", ")", "{", "// variables", "$", "folder", "=", "dirname", "(", "$", "file", ")", ";", "// ensure folder exists", "if", "(", "!", "file_exists", "(", "$", "folder", ")", ")", "{", "mkd...
Saves content to a file, updating file permissions to ensure a save @param string $file @param string $data
[ "Saves", "content", "to", "a", "file", "updating", "file", "permissions", "to", "ensure", "a", "save" ]
ebd3365265f8844f7d400d7d530605512a20011c
https://github.com/davestewart/laravel-sketchpad/blob/ebd3365265f8844f7d400d7d530605512a20011c/src/traits/SaveFileTrait.php#L14-L37
train
davestewart/laravel-sketchpad
src/utils/Options.php
Options.parse
public function parse($input) { $output = []; $options = explode('|', $input); foreach($options as $option) { $name = $option; $value = 1; if(strpos($option, ':') !== false) { list($name, $value) = explode(':', $option, 2); } if (strstr($value, ',') !== false) { $values = explode(',', $value); if (strstr($value, '=') !== false) { $pairs = []; foreach($values as $value) { list($n, $v) = explode('=', $value, 2); $pairs[$n] = $v; } $values = $pairs; } $value = $values; } $output[$name] = $value; } return $output; }
php
public function parse($input) { $output = []; $options = explode('|', $input); foreach($options as $option) { $name = $option; $value = 1; if(strpos($option, ':') !== false) { list($name, $value) = explode(':', $option, 2); } if (strstr($value, ',') !== false) { $values = explode(',', $value); if (strstr($value, '=') !== false) { $pairs = []; foreach($values as $value) { list($n, $v) = explode('=', $value, 2); $pairs[$n] = $v; } $values = $pairs; } $value = $values; } $output[$name] = $value; } return $output; }
[ "public", "function", "parse", "(", "$", "input", ")", "{", "$", "output", "=", "[", "]", ";", "$", "options", "=", "explode", "(", "'|'", ",", "$", "input", ")", ";", "foreach", "(", "$", "options", "as", "$", "option", ")", "{", "$", "name", ...
Converts string options to a hash Operation: - splits options by | - splits arguments by : - splits argument members by , - splits argument member names and values by = Example: index|html:path|pre:path,methods|values:One=1,Two=2,Three=3 @param $input @return array
[ "Converts", "string", "options", "to", "a", "hash" ]
ebd3365265f8844f7d400d7d530605512a20011c
https://github.com/davestewart/laravel-sketchpad/blob/ebd3365265f8844f7d400d7d530605512a20011c/src/utils/Options.php#L82-L112
train
davestewart/laravel-sketchpad
src/traits/ReflectionTraits.php
ReflectionTraits.getLabel
public function getLabel($default = null) { $label = $this->getTag('label'); if( ! $label ) { $label = $default ?: $this->ref->getName(); $label = preg_replace('/^(.+)Controller$/', '$1', $label); //$label = preg_replace('/_/', ' ', $label); //$label = preg_replace('/([a-z])([A-Z0-9])/', '$1 $2', $label); //$label = strtolower($label); } return $label; }
php
public function getLabel($default = null) { $label = $this->getTag('label'); if( ! $label ) { $label = $default ?: $this->ref->getName(); $label = preg_replace('/^(.+)Controller$/', '$1', $label); //$label = preg_replace('/_/', ' ', $label); //$label = preg_replace('/([a-z])([A-Z0-9])/', '$1 $2', $label); //$label = strtolower($label); } return $label; }
[ "public", "function", "getLabel", "(", "$", "default", "=", "null", ")", "{", "$", "label", "=", "$", "this", "->", "getTag", "(", "'label'", ")", ";", "if", "(", "!", "$", "label", ")", "{", "$", "label", "=", "$", "default", "?", ":", "$", "t...
Determines the label for the element Returns a @label parameter, if available, otherwise, humanizes the element name @param null $default @return null|string
[ "Determines", "the", "label", "for", "the", "element" ]
ebd3365265f8844f7d400d7d530605512a20011c
https://github.com/davestewart/laravel-sketchpad/blob/ebd3365265f8844f7d400d7d530605512a20011c/src/traits/ReflectionTraits.php#L61-L73
train
davestewart/laravel-sketchpad
src/traits/ReflectionTraits.php
ReflectionTraits.getTag
public function getTag($name) { $comment = $this->ref->getDocComment(); preg_match('/@' .$name. '\s+(.+)/', $comment, $matches); return $matches ? $matches[1] : null; }
php
public function getTag($name) { $comment = $this->ref->getDocComment(); preg_match('/@' .$name. '\s+(.+)/', $comment, $matches); return $matches ? $matches[1] : null; }
[ "public", "function", "getTag", "(", "$", "name", ")", "{", "$", "comment", "=", "$", "this", "->", "ref", "->", "getDocComment", "(", ")", ";", "preg_match", "(", "'/@'", ".", "$", "name", ".", "'\\s+(.+)/'", ",", "$", "comment", ",", "$", "matches"...
Gets the first available value of a tag @param string $name @return string|null
[ "Gets", "the", "first", "available", "value", "of", "a", "tag" ]
ebd3365265f8844f7d400d7d530605512a20011c
https://github.com/davestewart/laravel-sketchpad/blob/ebd3365265f8844f7d400d7d530605512a20011c/src/traits/ReflectionTraits.php#L81-L86
train
davestewart/laravel-sketchpad
src/objects/route/CallReference.php
CallReference.setMethod
public function setMethod($route) { // variables $methodUri = trim(substr($route, strlen($this->route)), '/'); $segments = explode(',', $methodUri); // properties $this->method = array_shift($segments); // return return $this; }
php
public function setMethod($route) { // variables $methodUri = trim(substr($route, strlen($this->route)), '/'); $segments = explode(',', $methodUri); // properties $this->method = array_shift($segments); // return return $this; }
[ "public", "function", "setMethod", "(", "$", "route", ")", "{", "// variables", "$", "methodUri", "=", "trim", "(", "substr", "(", "$", "route", ",", "strlen", "(", "$", "this", "->", "route", ")", ")", ",", "'/'", ")", ";", "$", "segments", "=", "...
Determines the method to call @param $route @return $this
[ "Determines", "the", "method", "to", "call" ]
ebd3365265f8844f7d400d7d530605512a20011c
https://github.com/davestewart/laravel-sketchpad/blob/ebd3365265f8844f7d400d7d530605512a20011c/src/objects/route/CallReference.php#L77-L88
train
davestewart/laravel-sketchpad
src/objects/route/CallReference.php
CallReference.setParams
public function setParams($params) { $this->params = []; foreach ($params as $param) { // variables $name = $param['name']; $type = $param['type']; $value = $param['value']; // properties $this->params[$name] = $this->convert($type, $value); } // return return $this; }
php
public function setParams($params) { $this->params = []; foreach ($params as $param) { // variables $name = $param['name']; $type = $param['type']; $value = $param['value']; // properties $this->params[$name] = $this->convert($type, $value); } // return return $this; }
[ "public", "function", "setParams", "(", "$", "params", ")", "{", "$", "this", "->", "params", "=", "[", "]", ";", "foreach", "(", "$", "params", "as", "$", "param", ")", "{", "// variables", "$", "name", "=", "$", "param", "[", "'name'", "]", ";", ...
Sets the calling parameters from the submitted front end data @param \StdClass[] $params @return $this
[ "Sets", "the", "calling", "parameters", "from", "the", "submitted", "front", "end", "data" ]
ebd3365265f8844f7d400d7d530605512a20011c
https://github.com/davestewart/laravel-sketchpad/blob/ebd3365265f8844f7d400d7d530605512a20011c/src/objects/route/CallReference.php#L96-L112
train
davestewart/laravel-sketchpad
src/objects/route/CallReference.php
CallReference.convert
protected function convert ($type, $value) { switch ($type) { case 'string': return (string) $value; case 'number': return is_float($value) ? (float) $value : (int) $value; case 'boolean': return $value === true || $value === 'true' || $value === '1' || $value === 'on'; default: if (is_float($value)) { return $this->convert('number', $value); } if (is_numeric($value)) { return strpos($value, '.') !== FALSE ? (float) $value : (int) $value; } if ($value === 'true' || $value === 'false') { return $value === 'true'; } if ($value === '') { return null; } } return $value; }
php
protected function convert ($type, $value) { switch ($type) { case 'string': return (string) $value; case 'number': return is_float($value) ? (float) $value : (int) $value; case 'boolean': return $value === true || $value === 'true' || $value === '1' || $value === 'on'; default: if (is_float($value)) { return $this->convert('number', $value); } if (is_numeric($value)) { return strpos($value, '.') !== FALSE ? (float) $value : (int) $value; } if ($value === 'true' || $value === 'false') { return $value === 'true'; } if ($value === '') { return null; } } return $value; }
[ "protected", "function", "convert", "(", "$", "type", ",", "$", "value", ")", "{", "switch", "(", "$", "type", ")", "{", "case", "'string'", ":", "return", "(", "string", ")", "$", "value", ";", "case", "'number'", ":", "return", "is_float", "(", "$"...
Utility used to convert values to the correct type @param string $type @param mixed $value @return mixed
[ "Utility", "used", "to", "convert", "values", "to", "the", "correct", "type" ]
ebd3365265f8844f7d400d7d530605512a20011c
https://github.com/davestewart/laravel-sketchpad/blob/ebd3365265f8844f7d400d7d530605512a20011c/src/objects/route/CallReference.php#L125-L161
train
davestewart/laravel-sketchpad
src/help/demo/ToolsController.php
ToolsController.viewUsers
public function viewUsers() { $users = \DB::table('users') ->select('id', 'name', 'email', 'created_at') ->limit(1) ->paginate(15); if($users) { tb($users); echo $users; return; } p('Unable to show users'); }
php
public function viewUsers() { $users = \DB::table('users') ->select('id', 'name', 'email', 'created_at') ->limit(1) ->paginate(15); if($users) { tb($users); echo $users; return; } p('Unable to show users'); }
[ "public", "function", "viewUsers", "(", ")", "{", "$", "users", "=", "\\", "DB", "::", "table", "(", "'users'", ")", "->", "select", "(", "'id'", ",", "'name'", ",", "'email'", ",", "'created_at'", ")", "->", "limit", "(", "1", ")", "->", "paginate",...
Show users in a table
[ "Show", "users", "in", "a", "table" ]
ebd3365265f8844f7d400d7d530605512a20011c
https://github.com/davestewart/laravel-sketchpad/blob/ebd3365265f8844f7d400d7d530605512a20011c/src/help/demo/ToolsController.php#L31-L46
train
davestewart/laravel-sketchpad
src/help/demo/ToolsController.php
ToolsController.browseFilesystem
public function browseFilesystem($path = '') { // helpers function getBreadcrumbs($base, $path) { $paths = ['/' => $base]; $path = trim($path, '/'); if ($path !== '') { $segments = explode('/', $path); $current = '/'; foreach($segments as $segment) { $current .= $segment . '/'; $paths[$current] = $segment; } } return $paths; } // paths $path = str_replace('../', '', $path); $path = '/' . trim(preg_replace('%[\\/]+%', '/', $path), '/'); $realpath = realpath(base_path($path)); $base = pathinfo(base_path())['basename']; // found if($realpath) { try { $objects = array_diff(scandir($realpath), ['.','..']); $breadcrumbs = getBreadcrumbs($base, $path); $folders = array_filter($objects, function($f) use ($realpath) { return is_dir($realpath . '/' . $f); }); $files = array_filter($objects, function($f) use ($realpath) { return is_file($realpath . '/' . $f); }); $path = rtrim($path, '/') . '/'; $parent = $path !== '/' ? preg_replace('%[^/]+/$%', '', $path) : '/'; return view('sketchpad::help/tools/folder', compact('parent', 'path', 'folders', 'files', 'breadcrumbs')); } catch(\Exception $e) { return "Unable to read folder '$path'"; } } // not found return "Path '$path' not found"; }
php
public function browseFilesystem($path = '') { // helpers function getBreadcrumbs($base, $path) { $paths = ['/' => $base]; $path = trim($path, '/'); if ($path !== '') { $segments = explode('/', $path); $current = '/'; foreach($segments as $segment) { $current .= $segment . '/'; $paths[$current] = $segment; } } return $paths; } // paths $path = str_replace('../', '', $path); $path = '/' . trim(preg_replace('%[\\/]+%', '/', $path), '/'); $realpath = realpath(base_path($path)); $base = pathinfo(base_path())['basename']; // found if($realpath) { try { $objects = array_diff(scandir($realpath), ['.','..']); $breadcrumbs = getBreadcrumbs($base, $path); $folders = array_filter($objects, function($f) use ($realpath) { return is_dir($realpath . '/' . $f); }); $files = array_filter($objects, function($f) use ($realpath) { return is_file($realpath . '/' . $f); }); $path = rtrim($path, '/') . '/'; $parent = $path !== '/' ? preg_replace('%[^/]+/$%', '', $path) : '/'; return view('sketchpad::help/tools/folder', compact('parent', 'path', 'folders', 'files', 'breadcrumbs')); } catch(\Exception $e) { return "Unable to read folder '$path'"; } } // not found return "Path '$path' not found"; }
[ "public", "function", "browseFilesystem", "(", "$", "path", "=", "''", ")", "{", "// helpers", "function", "getBreadcrumbs", "(", "$", "base", ",", "$", "path", ")", "{", "$", "paths", "=", "[", "'/'", "=>", "$", "base", "]", ";", "$", "path", "=", ...
Browse your local filesystem @param string $path @return View|string
[ "Browse", "your", "local", "filesystem" ]
ebd3365265f8844f7d400d7d530605512a20011c
https://github.com/davestewart/laravel-sketchpad/blob/ebd3365265f8844f7d400d7d530605512a20011c/src/help/demo/ToolsController.php#L83-L131
train
davestewart/laravel-sketchpad
src/help/demo/ToolsController.php
ToolsController.sketchpadSettings
public function sketchpadSettings(SketchpadConfig $config) { p('Settings:'); json($config->settings); p('Admin:'); json($config->admin); }
php
public function sketchpadSettings(SketchpadConfig $config) { p('Settings:'); json($config->settings); p('Admin:'); json($config->admin); }
[ "public", "function", "sketchpadSettings", "(", "SketchpadConfig", "$", "config", ")", "{", "p", "(", "'Settings:'", ")", ";", "json", "(", "$", "config", "->", "settings", ")", ";", "p", "(", "'Admin:'", ")", ";", "json", "(", "$", "config", "->", "ad...
Check your sketchpad settings
[ "Check", "your", "sketchpad", "settings" ]
ebd3365265f8844f7d400d7d530605512a20011c
https://github.com/davestewart/laravel-sketchpad/blob/ebd3365265f8844f7d400d7d530605512a20011c/src/help/demo/ToolsController.php#L146-L152
train
davestewart/laravel-sketchpad
src/help/docs/SetupController.php
SetupController.assets
public function assets(SketchpadConfig $config) { $assets = $config->settings->get('paths.assets'); $views = $config->settings->get('paths.views'); md('sketchpad::help/setup/assets', compact('assets', 'views')); }
php
public function assets(SketchpadConfig $config) { $assets = $config->settings->get('paths.assets'); $views = $config->settings->get('paths.views'); md('sketchpad::help/setup/assets', compact('assets', 'views')); }
[ "public", "function", "assets", "(", "SketchpadConfig", "$", "config", ")", "{", "$", "assets", "=", "$", "config", "->", "settings", "->", "get", "(", "'paths.assets'", ")", ";", "$", "views", "=", "$", "config", "->", "settings", "->", "get", "(", "'...
Load user scripts and styles to augment your Sketchpad development
[ "Load", "user", "scripts", "and", "styles", "to", "augment", "your", "Sketchpad", "development" ]
ebd3365265f8844f7d400d7d530605512a20011c
https://github.com/davestewart/laravel-sketchpad/blob/ebd3365265f8844f7d400d7d530605512a20011c/src/help/docs/SetupController.php#L42-L47
train
davestewart/laravel-sketchpad
src/help/docs/SetupController.php
SetupController.head
public function head(Paths $paths, SketchpadConfig $config) { $head = $config->getView('head'); $path = $paths->package('setup/views/head.blade.php'); $html = file_get_contents($path); md('sketchpad::help/setup/head', compact('head', 'html')); }
php
public function head(Paths $paths, SketchpadConfig $config) { $head = $config->getView('head'); $path = $paths->package('setup/views/head.blade.php'); $html = file_get_contents($path); md('sketchpad::help/setup/head', compact('head', 'html')); }
[ "public", "function", "head", "(", "Paths", "$", "paths", ",", "SketchpadConfig", "$", "config", ")", "{", "$", "head", "=", "$", "config", "->", "getView", "(", "'head'", ")", ";", "$", "path", "=", "$", "paths", "->", "package", "(", "'setup/views/he...
Add 3rd-party libraries, tracking or other head content
[ "Add", "3rd", "-", "party", "libraries", "tracking", "or", "other", "head", "content" ]
ebd3365265f8844f7d400d7d530605512a20011c
https://github.com/davestewart/laravel-sketchpad/blob/ebd3365265f8844f7d400d7d530605512a20011c/src/help/docs/SetupController.php#L82-L88
train
davestewart/laravel-sketchpad
src/utils/Html.php
Html.code
public static function code($source) { if (class_exists($source)) { @list ($class, $method, $comment) = func_get_args(); return is_string($method) ? Code::method($class, $method, $comment) : Code::classfile($class, $method); } else if (file_exists($source)) { @list ($path, $start, $end, $undent) = func_get_args(); return is_int($start) ? Code::section($path, $start, $end, $undent) : Code::file($path, $start); } return Code::output($source); }
php
public static function code($source) { if (class_exists($source)) { @list ($class, $method, $comment) = func_get_args(); return is_string($method) ? Code::method($class, $method, $comment) : Code::classfile($class, $method); } else if (file_exists($source)) { @list ($path, $start, $end, $undent) = func_get_args(); return is_int($start) ? Code::section($path, $start, $end, $undent) : Code::file($path, $start); } return Code::output($source); }
[ "public", "static", "function", "code", "(", "$", "source", ")", "{", "if", "(", "class_exists", "(", "$", "source", ")", ")", "{", "@", "list", "(", "$", "class", ",", "$", "method", ",", "$", "comment", ")", "=", "func_get_args", "(", ")", ";", ...
Return code with optional highlighting @param string $source @return string
[ "Return", "code", "with", "optional", "highlighting" ]
ebd3365265f8844f7d400d7d530605512a20011c
https://github.com/davestewart/laravel-sketchpad/blob/ebd3365265f8844f7d400d7d530605512a20011c/src/utils/Html.php#L55-L72
train
davestewart/laravel-sketchpad
src/utils/Html.php
Html.icon
public static function icon($name, $color = '') { if (is_bool($name)) { $color = $name ? 'success' : 'danger'; $name = $name ? 'check' : 'times'; } $class = "icon fa fa-$name"; $style = ''; if (preg_match('/(info|success|warning|danger)/', $color)) { $class .= ' text-' . $color; } else if ($color !== '') { $style = ' style="color:' .$color. '"'; } return '<i class="' .$class. '" ' .$style. '></i>'; }
php
public static function icon($name, $color = '') { if (is_bool($name)) { $color = $name ? 'success' : 'danger'; $name = $name ? 'check' : 'times'; } $class = "icon fa fa-$name"; $style = ''; if (preg_match('/(info|success|warning|danger)/', $color)) { $class .= ' text-' . $color; } else if ($color !== '') { $style = ' style="color:' .$color. '"'; } return '<i class="' .$class. '" ' .$style. '></i>'; }
[ "public", "static", "function", "icon", "(", "$", "name", ",", "$", "color", "=", "''", ")", "{", "if", "(", "is_bool", "(", "$", "name", ")", ")", "{", "$", "color", "=", "$", "name", "?", "'success'", ":", "'danger'", ";", "$", "name", "=", "...
Return a Font Awesome icon @param string|bool $name A FontAwesome icon name, or a boolean for colored tick/cross @param string $color An optional colour @return string
[ "Return", "a", "Font", "Awesome", "icon" ]
ebd3365265f8844f7d400d7d530605512a20011c
https://github.com/davestewart/laravel-sketchpad/blob/ebd3365265f8844f7d400d7d530605512a20011c/src/utils/Html.php#L104-L122
train
davestewart/laravel-sketchpad
src/utils/Html.php
Html.ls
public static function ls($values, $options = '') { $opts = new Options($options); $data = [ 'values' => $values, 'style' => $opts->get('style', ''), 'class' => $opts->get('class', ''), ]; if($opts->pre === 1) { $data['class'] .= ' pre'; } if($opts->wide) { $data['style'] .= ';width:100%;'; } return view('sketchpad::html.list', $data); }
php
public static function ls($values, $options = '') { $opts = new Options($options); $data = [ 'values' => $values, 'style' => $opts->get('style', ''), 'class' => $opts->get('class', ''), ]; if($opts->pre === 1) { $data['class'] .= ' pre'; } if($opts->wide) { $data['style'] .= ';width:100%;'; } return view('sketchpad::html.list', $data); }
[ "public", "static", "function", "ls", "(", "$", "values", ",", "$", "options", "=", "''", ")", "{", "$", "opts", "=", "new", "Options", "(", "$", "options", ")", ";", "$", "data", "=", "[", "'values'", "=>", "$", "values", ",", "'style'", "=>", "...
List an object's properties in a nicely formatted table @param mixed $values @param string $options @return string
[ "List", "an", "object", "s", "properties", "in", "a", "nicely", "formatted", "table" ]
ebd3365265f8844f7d400d7d530605512a20011c
https://github.com/davestewart/laravel-sketchpad/blob/ebd3365265f8844f7d400d7d530605512a20011c/src/utils/Html.php#L164-L182
train