_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q265500 | SerializerExceptionRenderer.renderValidationSerializerException | test | protected function renderValidationSerializerException(ValidationBaseSerializerException $error) {
if ($this->isJsonApiRequest()) {
return $this->renderValidationSerializerAsJsonApi($error);
}
if ($this->isJsonRequest()) {
return $this->renderValidationSerializerAsJson($error);
}
return $this->defaultValidationSerializerRender($error);
} | php | {
"resource": ""
} |
q265501 | SerializerExceptionRenderer.renderHttpAsJson | test | protected function renderHttpAsJson(HttpException $error) {
// Set the view class as json and render as json
$this->controller->viewClass = 'Json';
$this->controller->response->type('json');
$url = $this->controller->request->here();
$code = ($error->getCode() >= 400 && $error->getCode() < 506) ? $error->getCode() : 500;
$this->controller->response->statusCode($code);
$this->controller->set(array(
'code' => $code,
'name' => h(get_class($error)),
'message' => h($error->getMessage()),
'url' => h($url),
'error' => $error,
'_serialize' => array('code', 'name', 'message', 'url')
));
$this->_outputMessage($this->template);
} | php | {
"resource": ""
} |
q265502 | SerializerExceptionRenderer.renderHttpAsJsonApi | test | protected function renderHttpAsJsonApi(HttpException $error) {
// Add a response type for JSON API
$this->controller->response->type(array('jsonapi' => 'application/vnd.api+json'));
// Set the controller to response as JSON API
$this->controller->response->type('jsonapi');
// Set the correct Status Code
$this->controller->response->statusCode($error->getCode());
// set the errors object to match JsonApi's standard
$errors = array(
'errors' => array(
'id' => null,
'href' => null,
'status' => h($error->getCode()),
'code' => h(get_class($error)),
'title' => h($error->getMessage()),
'detail' => h($error->getMessage()),
'links' => array(),
'paths' => array(),
),
);
// json encode the errors
$jsonEncodedErrors = json_encode($errors);
// set the body to the json encoded errors
$this->controller->response->body($jsonEncodedErrors);
return $this->controller->response->send();
} | php | {
"resource": ""
} |
q265503 | SerializerExceptionRenderer.renderCakeAsJson | test | protected function renderCakeAsJson(CakeException $error) {
// Set the view class as json and render as json
$this->controller->viewClass = 'Json';
$this->controller->response->type('json');
$url = $this->controller->request->here();
$code = ($error->getCode() >= 400 && $error->getCode() < 506) ? $error->getCode() : 500;
$this->controller->response->statusCode($code);
$this->controller->set(array(
'code' => $code,
'name' => h(get_class($error)),
'message' => h($error->getMessage()),
'url' => h($url),
'error' => $error,
'_serialize' => array('code', 'name', 'message', 'url')
));
$this->controller->set($error->getAttributes());
$this->_outputMessage($this->template);
} | php | {
"resource": ""
} |
q265504 | SerializerExceptionRenderer.renderCakeAsJsonApi | test | protected function renderCakeAsJsonApi(CakeException $error) {
// Add a response type for JSON API
$this->controller->response->type(array('jsonapi' => 'application/vnd.api+json'));
// Set the controller to response as JSON API
$this->controller->response->type('jsonapi');
// Set the correct Status Code
$this->controller->response->statusCode($error->getCode());
// set the errors object to match JsonApi's standard
$errors = array(
'errors' => array(
'id' => null,
'href' => null,
'status' => h($error->getCode()),
'code' => h(get_class($error)),
'title' => h($error->getMessage()),
'detail' => h($error->getAttributes()),
'links' => array(),
'paths' => array(),
),
);
// json encode the errors
$jsonEncodedErrors = json_encode($errors);
// set the body to the json encoded errors
$this->controller->response->body($jsonEncodedErrors);
return $this->controller->response->send();
} | php | {
"resource": ""
} |
q265505 | SerializerExceptionRenderer.defaultSerializerRender | test | protected function defaultSerializerRender(BaseSerializerException $error) {
$this->controller->response->statusCode($error->status());
// set the errors object to match JsonApi's expectations
$this->controller->set('id', $error->id());
$this->controller->set('href', $error->href());
$this->controller->set('status', $error->status());
$this->controller->set('code', $error->code());
$this->controller->set('title', $error->title());
$this->controller->set('detail', $error->detail());
$this->controller->set('links', $error->links());
$this->controller->set('paths', $error->paths());
$this->controller->set('error', $error);
$this->controller->set('url', $this->controller->request->here());
if (empty($template)) {
$template = "SerializersErrors./Errors/serializer_exception";
}
$this->controller->render($template);
$this->controller->afterFilter();
return $this->controller->response->send();
} | php | {
"resource": ""
} |
q265506 | SerializerExceptionRenderer.renderSerializerAsJson | test | protected function renderSerializerAsJson(BaseSerializerException $error) {
// Set the view class as json and render as json
$this->controller->viewClass = 'Json';
$this->controller->response->type('json');
$this->controller->response->statusCode($error->status());
// set all the values we have from our exception to populate the json object
$this->controller->set('id', h($error->id()));
$this->controller->set('href', h($error->href()));
$this->controller->set('status', h($error->status()));
$this->controller->set('code', h($error->code()));
$this->controller->set('title', h($error->title()));
$this->controller->set('detail', h($error->detail()));
$this->controller->set('links', h($error->links()));
$this->controller->set('paths', h($error->paths()));
$this->controller->set('_serialize', array(
'id', 'href', 'status', 'code', 'title ', 'detail', 'links', 'paths'
));
if (empty($template)) {
$template = "SerializersErrors./Errors/serializer_exception";
}
$this->controller->render($template);
$this->controller->afterFilter();
return $this->controller->response->send();
} | php | {
"resource": ""
} |
q265507 | SerializerExceptionRenderer.renderSerializerAsJsonApi | test | protected function renderSerializerAsJsonApi(BaseSerializerException $error) {
// Add a response type for JSON API
$this->controller->response->type(array('jsonapi' => 'application/vnd.api+json'));
// Set the controller to response as JSON API
$this->controller->response->type('jsonapi');
// Set the correct Status Code
$this->controller->response->statusCode($error->status());
// set the errors object to match JsonApi's standard
$errors = array(
'errors' => array(
array(
'id' => h($error->id()),
'href' => h($error->href()),
'status' => h($error->status()),
'code' => h($error->code()),
'title' => h($error->title()),
'detail' => h($error->detail()),
'links' => $error->links(),
'paths' => $error->paths(),
),
),
);
// json encode the errors
$jsonEncodedErrors = json_encode($errors);
// set the body to the json encoded errors
$this->controller->response->body($jsonEncodedErrors);
return $this->controller->response->send();
} | php | {
"resource": ""
} |
q265508 | SerializerExceptionRenderer.defaultValidationSerializerRender | test | protected function defaultValidationSerializerRender(ValidationBaseSerializerException $error) {
$this->addHttpCodes();
$this->controller->response->statusCode($error->status());
// set the errors object to match JsonApi's expectations
$this->controller->set('title', $error->title());
$this->controller->set('validationErrors', $error->validationErrors());
$this->controller->set('status', $error->status());
$this->controller->set('error', $error);
$this->controller->set('url', $this->controller->request->here());
if (empty($template)) {
$template = "SerializersErrors./Errors/validation_serializer_exception";
}
$this->controller->render($template);
$this->controller->afterFilter();
return $this->controller->response->send();
} | php | {
"resource": ""
} |
q265509 | SerializerExceptionRenderer.renderValidationSerializerAsJson | test | protected function renderValidationSerializerAsJson(ValidationBaseSerializerException $error) {
// Set the view class as json and render as json
$this->controller->viewClass = 'Json';
$this->controller->response->type('json');
$this->addHttpCodes();
$this->controller->response->statusCode($error->status());
// set the errors object to match JsonApi's standard
$errors = array(
'errors' => $error->validationErrors(),
);
// json encode the errors
$jsonEncodedErrors = json_encode($errors);
// set the body to the json encoded errors
$this->controller->response->body($jsonEncodedErrors);
return $this->controller->response->send();
} | php | {
"resource": ""
} |
q265510 | SerializerExceptionRenderer.renderValidationSerializerAsJsonApi | test | protected function renderValidationSerializerAsJsonApi(ValidationBaseSerializerException $error) {
// Add a response type for JSON API
$this->controller->response->type(array('jsonapi' => 'application/vnd.api+json'));
// Set the controller to response as JSON API
$this->controller->response->type('jsonapi');
$this->addHttpCodes();
$this->controller->response->statusCode($error->status());
// set the errors object to match JsonApi's standard
$errors = array(
'errors' => array(
array(
'id' => h($error->id()),
'href' => h($error->href()),
'status' => h($error->status()),
'code' => h($error->code()),
'title' => h($error->title()),
'detail' => h($error->validationErrors()),
'links' => h($error->links()),
'paths' => h($error->paths()),
),
),
);
// json encode the errors
$jsonEncodedErrors = json_encode($errors);
// set the body to the json encoded errors
$this->controller->response->body($jsonEncodedErrors);
return $this->controller->response->send();
} | php | {
"resource": ""
} |
q265511 | SessionManager.openSessionByID | test | public function openSessionByID($sessionID, $userProfile = null)
{
$session = $this->driver->openSessionByID(
$sessionID,
$this,
$userProfile
);
if ($session == null) {
$this->invalidSessionAccessed();
}
return $session;
} | php | {
"resource": ""
} |
q265512 | SessionManager.createSession | test | function createSession(array $cookieData, $userProfile = null)
{
if (!array_key_exists($this->sessionConfig->getSessionName(), $cookieData)) {
return $this->driver->createSession($this, $userProfile);
}
$sessionID = $cookieData[$this->sessionConfig->getSessionName()];
$existingSession = $this->openSessionByID($sessionID, $userProfile);
if ($existingSession !== null) {
return $existingSession;
}
$this->invalidSessionAccessed();
return $this->driver->createSession($this, $userProfile);
} | php | {
"resource": ""
} |
q265513 | Title.prepareText | test | protected function prepareText(&$text) {
// check if it is a string
if (!is_string($text)) {
// it is not, raise a flag
return false;
}
// trim any front or ending spaces
$text = trim($text);
// if there is no text, no need to continue
if (strlen($text) == 0) {
// there is not text, raise a flag
return false;
}
return true;
} | php | {
"resource": ""
} |
q265514 | Title.display | test | public function display($text) {
// prepare the text for the particular style of text
// if it returns false, the text is bad
if (!$this->prepareText($text)) {
// chaining
return $this;
}
// justify the text
$text = $this->clio->justify($text, $this->justification);
// create the specified number of lines before
if ($this->spaceBefore > 0) {
// move down the space before number of lines
$this->clio->newLine($this->spaceBefore);
}
// calculate any empty lines needed to create the height
$top = $bottom = 0;
// if there was anything higher than one requiring empty styled lines
if ($this->height > 1) {
// take off the actual title line
$spaces = $this->height - 1;
// the top will be the base value of dividing by two
$top = intdiv($spaces,2);
// the bottom will be that base value + the remainder
$bottom = intdiv($spaces,2) + ($spaces % 2);
}
// set up the styling
$this->clio->style($this->style);
// display any empty lines needed above the title for the height
$this->displayEmptyLines($top);
// display the title text
$this->clio->line($text);
// display any empty lines needed below the title for the height
$this->displayEmptyLines($bottom);
// clear the formatting
$this->clio->clear();
// if there is space after
if ($this->spaceAfter > 0) {
// display the space after
$this->clio->newLine($this->spaceAfter);
}
// chaining
return $this;
} | php | {
"resource": ""
} |
q265515 | Title.displayEmptyLines | test | private function displayEmptyLines($lines)
{
// create an empty line
$emptyLine = str_pad(" ", $this->clio->getWidth());
// if there is more than one line
for ($i = 0; $i < $lines; ++$i) {
// generate an empty line
$this->clio->line($emptyLine);
}
} | php | {
"resource": ""
} |
q265516 | ConsoleProvider.init | test | public function init(Application $cli, $commands = [])
{
$this->cli = $cli;
$this->commands = $commands;
} | php | {
"resource": ""
} |
q265517 | KernelSubscriber.onKernelResponse | test | public function onKernelResponse(FilterResponseEvent $event)
{
if ($event->isMasterRequest()) {
$request = $event->getRequest();
$response = $event->getResponse();
if ($request->isXmlHttpRequest() && !$response->isRedirection()) {
// flash messages
if ($request->hasSession() && !$response->headers->has('X-Flash-Messages')) {
$this->setFlashMessageHeader($response, $request->getSession());
}
// title, fullTitle
$this->setTitleHeaders($response);
// exception info (debug only)
if ($this->debug && $this->lastException) {
$this->setExceptionHeader($response, $this->lastException);
$this->lastException = null;
}
}
}
} | php | {
"resource": ""
} |
q265518 | DebugBarProvider.init | test | public function init(StandardDebugBar $debugBar){
$this->debugBar = $debugBar;
$this->debugBarRenderer = $debugBar->getJavascriptRenderer();
} | php | {
"resource": ""
} |
q265519 | SessionManager.sessionStart | test | public static function sessionStart($name, $lifetime = 0, $path = '/', $domain = null, $secure = null)
{
// Set the cookie name before we start.
session_name($name . '_Session');
// Set the domain to default to the current domain.
$domain = isset($domain) ? $domain : $_SERVER['SERVER_NAME'];
// Set the default secure value to whether the site is being accessed with SSL
$secure = isset($secure) ? $secure : isset($_SERVER['HTTPS']);
// Set the cookie settings and start the session
session_set_cookie_params($lifetime, $path, $domain, $secure, true);
$id = session_id();
if(empty($id)) {
session_start();
}
// Make sure the session hasn't expired, and destroy it if it has
if (self::validateSession()) {
// Check to see if the session is new or a hijacking attempt
if (!self::preventHijacking()) {
// Reset session data and regenerate id
$_SESSION = array();
$_SESSION['ipAddress'] = $_SERVER['REMOTE_ADDR'];
$_SESSION['userAgent'] = $_SERVER['HTTP_USER_AGENT'];
self::regenerateSession();
// Give a 5% chance of the session id changing on any request
} elseif (self::shouldRandomlyRegenerate()) {
self::regenerateSession();
}
} else {
self::destroySession();
}
} | php | {
"resource": ""
} |
q265520 | SessionManager.preventHijacking | test | private static function preventHijacking()
{
if (!isset($_SESSION['ipAddress']) || !isset($_SESSION['userAgent'])) {
return false;
}
if ($_SESSION['ipAddress'] != $_SERVER['REMOTE_ADDR']) {
return false;
}
if ($_SESSION['userAgent'] != $_SERVER['HTTP_USER_AGENT']) {
return false;
}
return true;
} | php | {
"resource": ""
} |
q265521 | SessionManager.regenerateSession | test | private static function regenerateSession()
{
// If this session is obsolete it means there already is a new id
if (isset($_SESSION['OBSOLETE']) && $_SESSION['OBSOLETE'] == true) {
return;
}
// Set current session to expire in 10 seconds
$_SESSION['OBSOLETE'] = true;
$_SESSION['EXPIRES'] = time() + 10;
// Create new session without destroying the old one
session_regenerate_id(false);
// Grab current session ID and close both sessions to allow other scripts to use them
$newSession = session_id();
session_write_close();
// Set session ID to the new one, and start it back up again
session_id($newSession);
session_start();
// Now we unset the obsolete and expiration values for the session we want to keep
unset($_SESSION['OBSOLETE']);
unset($_SESSION['EXPIRES']);
} | php | {
"resource": ""
} |
q265522 | SessionManager.validateSession | test | private static function validateSession()
{
if (isset($_SESSION['OBSOLETE']) && !isset($_SESSION['EXPIRES'])) {
return false;
}
if (isset($_SESSION['EXPIRES']) && $_SESSION['EXPIRES'] < time()) {
return false;
}
return true;
} | php | {
"resource": ""
} |
q265523 | Network.linkLayers | test | public function linkLayers()
{
for ($i = 1; $i < count($this->structure); $i++) {
$this->layers[$i]->bind($this->layers[$i - 1]);
}
} | php | {
"resource": ""
} |
q265524 | Request._paramBackbone | test | protected function _paramBackbone($key)
{
if (isset($this->_request['model'])) {
$model = json_decode($this->_request['model'], true);
return $model[$key];
}
return null;
} | php | {
"resource": ""
} |
q265525 | publish.register | test | public static function register( $px, $json ){
// プラグイン設定の初期化
if( !is_object(@$json) ){
$json = json_decode('{}');
}
if( !is_array(@$json->paths_ignore) ){
$json->paths_ignore = array();
}
// var_dump($json);
$self = new self( $px, $json );
$px->pxcmd()->register('publish', array($self, 'exec_home'));
} | php | {
"resource": ""
} |
q265526 | publish.cli_header | test | private function cli_header(){
ob_start();
print $this->px->pxcmd()->get_cli_header();
print 'publish directory(tmp): '.$this->path_tmp_publish."\n";
print 'lockfile: '.$this->path_lockfile."\n";
print 'publish directory: '.$this->path_publish_dir."\n";
print 'domain: '.$this->domain."\n";
print 'docroot directory: '.$this->path_docroot."\n";
print 'ignore: '.join(', ', $this->plugin_conf->paths_ignore)."\n";
print 'region: '.join(', ', $this->paths_region)."\n";
print 'ignore (tmp): '.join(', ', $this->paths_ignore)."\n";
print 'keep cache: '.($this->flg_keep_cache ? 'true' : 'false')."\n";
print '------------'."\n";
flush();
return ob_get_clean();
} | php | {
"resource": ""
} |
q265527 | ExampleTokenParser.parseRawBody | test | private function parseRawBody($startLine)
{
$templateSource = \file_get_contents($this->parser->getStream()->getSourceContext()->getPath());
// parse tag contents
\preg_match(
'/\\s*\\{%\s*example\\s*%\\}(.*?)\\s*\\{%\\s*endexample\\s*%\\}/s',
\implode(
"\n",
\array_slice(
\preg_split('/\\n|\\r\\n?/', $templateSource),
$startLine - 1,
$this->parser->getCurrentToken()->getLine() - $startLine + 1
)
),
$match
);
if (isset($match[1])) {
return $this->removeExtraIndentation($match[1]);
}
return '';
} | php | {
"resource": ""
} |
q265528 | ExampleTokenParser.removeExtraIndentation | test | private function removeExtraIndentation($string)
{
$lines = \preg_split('/\\n|\\r\\n?/', $string);
// determine indentation length
$indentLen = null;
for ($i = 0; isset($lines[$i]); ++$i) {
if ('' !== \trim($lines[$i])) {
\preg_match('/^\\s*/', $lines[$i], $match);
$indentLen = \strlen($match[0]);
break;
}
}
if (null !== $indentLen) {
// cut each line
$out = '';
for (; isset($lines[$i]); ++$i) {
if (\substr($lines[$i], 0, $indentLen) === $match[0]) {
$out .= \substr($lines[$i], $indentLen);
} else {
$out .= $lines[$i];
}
$out .= "\n";
}
return $out;
}
return $string;
} | php | {
"resource": ""
} |
q265529 | CorrelationIdHTTPlug.handleRequest | test | public function handleRequest(RequestInterface $request, callable $next, callable $first)
{
$headers = [
$this->correlationEntryName->parent() => $this->requestIdentifier->current(),
$this->correlationEntryName->root() => $this->selectBestRootHeaderValue(),
];
foreach ($headers as $headerName => $headerValue) {
$request = $request->withHeader($headerName, $headerValue);
}
return $next($request);
} | php | {
"resource": ""
} |
q265530 | Url.parseQueryStringFromUrl | test | public static function parseQueryStringFromUrl($url)
{
$query = (string) parse_url($url, \PHP_URL_QUERY);
parse_str($query, $result);
return $result;
} | php | {
"resource": ""
} |
q265531 | theme.bind | test | private function bind( $px ){
$theme = $this;
ob_start();
include( $this->path_tpl.$this->page['layout'].'.html' );
$src = ob_get_clean();
return $src;
} | php | {
"resource": ""
} |
q265532 | Route.getMatch | test | public function getMatch($uri)
{
$expression = $this->pattern->getExpression();
$matches = [];
if (preg_match($expression, $uri, $matches) === 0) {
return false;
}
$matches = $this->cleanMatches($matches);
$matches = $this->removeNoise($matches);
return $matches + $this->defaults;
} | php | {
"resource": ""
} |
q265533 | Justification.getJustificationConstant | test | public static function getJustificationConstant($value) {
// if the value coming in, is a integer, ensure it is one of the constants
if (is_int($value)) {
// get the justification integer values
$values = array_values(self::$justificationConstants);
// if the integer submitted is one of those values, return it
if (in_array($value, $values)) {
// return the valid value
return $value;
}
}
// if the value coming in is a string
else if (is_string($value)) {
// trim the string
$value = trim($value);
// transform to uppercase
$value = strtoupper($value);
// if it is in the array of string values
if (isset(self::$justificationConstants[$value])) {
// return the matching integer value
return self::$justificationConstants[$value];
} else {
// not a valid string
return self::LEFT;
}
} else {
// something went wrong, return left
return self::LEFT;
}
return self::LEFT;
} | php | {
"resource": ""
} |
q265534 | Crawler.listLocalFiles | test | public function listLocalFiles(){
$files = array();
$dir = dir($this->docsHome);
while (false !== ($file = $dir->read())) {
if(substr($file, -4)==".pdf"){
$files[] = array('path'=>$this->docsHome, 'fileName'=>$file);
}
}
return $files;
} | php | {
"resource": ""
} |
q265535 | Crawler.extractDocumentsLink | test | private function extractDocumentsLink($html){
$links = array();
//preg_match_all("#<a\ href=\"(.*)\.pdf\"#", $html, $matches);
preg_match_all("#<a\ href=\"(.*)\"#", $html, $matches);
foreach($matches[1] as $f) {
$pospdf = strpos($f,".pdf");
if($pospdf !== false) {
$f = substr($f, 0, $pospdf + 4);
if (!$this->excludeLink($f)) {
$links[] = $f;
}
}
}
return $links;
} | php | {
"resource": ""
} |
q265536 | Crawler.excludeLink | test | private function excludeLink($href)
{
//If href string contains any of the 'words' in $excludes array, return true
$excluded = false;
foreach ($this->excludes as $word) {
if (strpos($href, $word) !== false) {
$excluded = true;
break;
}
}
return $excluded;
} | php | {
"resource": ""
} |
q265537 | Crawler.saveFile | test | private function saveFile($filename, $content, $hash){
$ruta = realpath($this->docsHome).'/'.$hash."-".$filename;
file_put_contents($ruta, $content);
} | php | {
"resource": ""
} |
q265538 | Crawler.existePdf | test | private function existePdf($filename, $hash){
$ruta = realpath($this->docsHome).'/'.$hash."-".$filename;
return file_exists($ruta);
} | php | {
"resource": ""
} |
q265539 | OrderedList.getNextOrderedNumber | test | protected function getNextOrderedNumber() {
// see if the current nesting has an entry in the orderedNumbers array
if (array_key_exists($this->nesting, $this->orderedNumbers)) {
// it does, so increase the number by 1
$this->orderedNumbers[$this->nesting] = $this->orderedNumbers[$this->nesting] + 1;
} else {
// it doesn't, so start a new index and initialize the number at 1
$this->orderedNumbers[$this->nesting] = 1;
}
// if this is the second level nesting...
if ($this->nesting === 2) {
// return a character starting with a
return chr(96 + $this->orderedNumbers[$this->nesting]);
// if this is the fourth level nesting
} else if ($this->nesting === 4) {
// return a character starting with A
return chr(64 + $this->orderedNumbers[$this->nesting]);
// otherwise use numbers for nesting level 1,3,5 and greater
} else {
// return the current number for this nesting
return $this->orderedNumbers[$this->nesting];
}
} | php | {
"resource": ""
} |
q265540 | OrderedList.end | test | public function end() {
// remove this ordered number tracking for this nesting
if (array_key_exists($this->nesting, $this->orderedNumbers)) {
// remove the item off the array
unset ($this->orderedNumbers[$this->nesting]);
}
// close the start
parent::end();
// chaining
return $this;
} | php | {
"resource": ""
} |
q265541 | Paragraph.display | test | public function display($text) {
// if trimming was desired
if ($this->trim) {
// trim any front or ending spaces
$text = trim($text);
}
// if there is no text, no need to continue
if (strlen($text) == 0) {
// no need to continue
return $this;
}
// wordwrap to the width of the html screen
$text = $this->clio->wordwrap($text, $this->clio->getWidth(), false);
// now get the lines that have been wordwrapped
$lines = explode("\n",$text);
// shortcut to the width
$width = $this->clio->getWidth();
// start the justified version of the wrapped text
$justifiedText = "";
// create an empty line for space after
$emptyLine = str_pad(" ",$this->clio->getWidth());
// shortcut
$numLines = count($lines);
// go through each line
for ($i=0; $i<$numLines; ++$i) {
// get the next line
$next = $lines[$i];
// ask Clio to justify the text and pad to the edge
$justifiedText .= $this->clio->justify($next,"left",$width) . "\n";
// if this is not the last line
// if ($i < ($numLines-1)) {
//
// // add a new line (the last one is left for space after
// $justifiedText .= "\n";
// }n
}
// now display the text
$this->displayWithStyling($justifiedText);
$this->nl($this->spaceAfter);
// chaining
return $this;
} | php | {
"resource": ""
} |
q265542 | Paragraph.nl | test | public function nl($count = 1) {
// create an empty line for space after
$emptyLine = str_pad(" ",$this->clio->getWidth()) . "\n";
// go through each line
for ($i=0; $i<$count; ++$i) {
// display an empty line, so the styling carries through to the right edge
$this->displayWithStyling($emptyLine);
}
} | php | {
"resource": ""
} |
q265543 | LinearRegression.fit | test | public function fit(DataSet $dataSet, float $learningRate = 0.0): AlgorithmsInterface
{
$outputSize = count($dataSet->getMapper()->getOutputKeys());
if ($outputSize !== 1) {
throw new WrongUsageException('Linear regression assumes only one output, ' . $outputSize . ' given');
}
if (count($dataSet->getMapper()->getDimensionKeys()) === 1) {
$this
->calculator
->using($dataSet)
->calculate(new Mean())
->then(new SimpleLinearCoefficients());
;
} else {
$this->coefficients = $this
->calculator
->using($dataSet)
->calculate(new MultipleLinearCoefficients())
->getResult()
->last()
;
}
$this->coefficients = $this->calculator->getResult()->last();
return $this;
} | php | {
"resource": ""
} |
q265544 | LinearRegression.predict | test | public function predict(DataSet $dataSet)
{
foreach ($dataSet as $instance) {
$prediction = $this
->calculator
->calculate(new LinearPrediction($instance->getDimensions(), $this->coefficients))
->getResult()
->last()
;
$instance->addResult(
static::class,
[
'type' => self::PREDICTION,
'result' => $prediction
]
);
}
$this->calculator->using($dataSet)->calculate(new Benchmark(LinearRegression::class));
$results = $this->calculator->getResult()->of(Benchmark::class);
$this->accuracy = $results[Benchmark::ACCURACY] ?? 0;
$this->rmse = $results[Benchmark::RMSE] ?? 0;
} | php | {
"resource": ""
} |
q265545 | PDOHandler.initialize | test | private function initialize()
{
$this->pdo->exec(
'CREATE TABLE IF NOT EXISTS `'.$this->table.'` '
.'(id INTEGER PRIMARY KEY AUTO_INCREMENT, channel VARCHAR(255),level_name VARCHAR(255), level INTEGER, message LONGTEXT, date DATETIME)'
);
//Read out actual columns
$actualFields = array();
$rs = $this->pdo->query('SELECT * FROM `'.$this->table.'` LIMIT 0');
for ($i = 0; $i < $rs->columnCount(); $i++) {
$col = $rs->getColumnMeta($i);
$actualFields[] = $col['name'];
}
//Calculate changed entries
$removedColumns = array_diff(
$actualFields,
$this->additionalFields,
array('id', 'channel', 'level','level_name', 'message', 'date')
);
$addedColumns = array_diff($this->additionalFields, $actualFields);
//Remove columns
if (!empty($removedColumns)) {
foreach ($removedColumns as $c) {
$this->pdo->exec('ALTER TABLE `'.$this->table.'` DROP `'.$c.'`;');
}
}
//Add columns
if (!empty($addedColumns)) {
foreach ($addedColumns as $c) {
$this->pdo->exec('ALTER TABLE `'.$this->table.'` add `'.$c.'` TEXT NULL DEFAULT NULL;');
}
}
//Prepare statement
$columns = "";
$fields = "";
foreach ($this->additionalFields as $f) {
$columns.= ", $f";
$fields.= ", :$f";
}
$this->statement = $this->pdo->prepare(
'INSERT INTO `'.$this->table.'` (channel, level, level_name, message, date'.$columns.')
VALUES (:channel, :level, :level_name, :message, :date'.$fields.')'
);
$this->initialized = true;
} | php | {
"resource": ""
} |
q265546 | PDOHandler.write | test | protected function write(array $record)
{
if (!$this->initialized) {
$this->initialize();
}
//'context' contains the array
$contentArray = array_merge(array(
'channel' => $record['channel'],
'level' => $record['level'],
'level_name' => $record['level_name'],
'message' => $record['message'],
'date' => $record['datetime']->format('Y-m-d H:i:s')
), $record['context']);
//Fill content array with "null" values if not provided
$contentArray = $contentArray + array_combine(
$this->additionalFields,
array_fill(0, count($this->additionalFields), null)
);
$this->statement->execute($contentArray);
} | php | {
"resource": ""
} |
q265547 | BulletedList.drawListItem | test | protected function drawListItem($bullet, $text) {
// determine the blank space indentation
$indentation = $this->createIndentation();
// In unordered list, the bullet can be specified
$left = $indentation . $bullet;
// determine the width of the bullet text
$bulletTextArea = $this->clio->getWidth() - strlen($left);
// word wrap the rest of the bullet
$text = $this->clio->wordwrap($text,$bulletTextArea, false);
// create an empty string that is the same with of the bullet
$emptyBullet = str_pad("",strlen($bullet));
// replace all newlines with a newline then indentation, then an empty bullet
$text = str_replace("\n", "\n" . $indentation . $emptyBullet, $text);
// show the bullet and text on multiple lines (if needed)
$this->clio->display($left . $text)->newLine();
} | php | {
"resource": ""
} |
q265548 | BulletedList.start | test | public function start($text = null) {
// if text was defined and it the first level of nesting
if ($text && ($this->nesting === 0)) {
// display the text with any markup
$this->clio->display($text)->newLine();
}
// add one to the nesting
++$this->nesting;
// chaining
return $this;
} | php | {
"resource": ""
} |
q265549 | CacheProvider.init | test | public function init($config = [], $use)
{
$this->config = $config;
$this->cache = $this->getCache($use);
$this->app->addAlias($use, $config['drivers'][$use]['class']);
} | php | {
"resource": ""
} |
q265550 | ImageSize.get | test | public static function get($name)
{
$name = (strtolower($name) === self::SIZE_ORIG) ? self::SIZE_ORIG : strtoupper($name);
return isset(self::$allowedSize[$name]) ? self::$allowedSize[$name] : null;
} | php | {
"resource": ""
} |
q265551 | Form.buildFormForSection | test | public function buildFormForSection(
string $forHandle,
RequestStack $requestStack,
SectionFormOptions $sectionFormOptions = null,
bool $csrfProtection = true
): FormInterface {
$sectionConfig = $this->getSectionConfig($forHandle);
$section = $this->getSection($sectionConfig->getFullyQualifiedClassName());
// If we have a slug, it means we are updating something.
// Prep so we can get the correct $sectionEntity
$slug = null;
if ($sectionFormOptions !== null) {
try {
$slug = $sectionFormOptions->getSlug();
} catch (\Exception $exception) {
$slug = null;
}
}
// If we hava an id, it means we are updating something.
// Prep so we can get the correct $sectionEntity
$id = null;
if ($sectionFormOptions !== null) {
try {
$id = $sectionFormOptions->getId();
} catch (\Exception $exception) {
$id = null;
}
}
$sectionEntity = $this->getSectionEntity(
$sectionConfig->getFullyQualifiedClassName(),
$section,
$slug,
$id
);
$factory = $this->getFormFactory($requestStack);
$form = $factory
->createBuilder(
FormType::class,
$sectionEntity,
[
'method' => 'POST',
'attr' => [
'novalidate' => 'novalidate'
],
'csrf_protection' => $csrfProtection,
'csrf_field_name' => 'token',
'csrf_token_id' => 'tardigrades',
'allow_extra_fields' => true // We need to allow extra fields for extra section fields (ignored in the generators)
]
);
/** @var FieldInterface $field */
foreach ($section->getFields() as $field) {
$fieldTypeFullyQualifiedClassName = (string) $field
->getFieldType()
->getFullyQualifiedClassName();
/** @var FieldTypeInterface $fieldType */
$fieldType = new $fieldTypeFullyQualifiedClassName;
$fieldType->setConfig($field->getConfig());
$fieldType->addToForm(
$form,
$section,
$sectionEntity,
$this->sectionManager,
$this->readSection,
$requestStack->getCurrentRequest()
);
}
$form->add('save', SubmitType::class);
return $form->getForm();
} | php | {
"resource": ""
} |
q265552 | Form.getFormFactory | test | private function getFormFactory(RequestStack $requestStack): FormFactory
{
$factory = $this->formFactory;
if (empty($this->formFactory)) {
$validatorBuilder = Validation::createValidatorBuilder();
// Loads validator metadata from entity static method
$validatorBuilder->addMethodMapping('loadValidatorMetadata');
$validator = $validatorBuilder->getValidator();
if (!$session = $requestStack->getCurrentRequest()->getSession()) {
$session = new Session();
}
$csrfGenerator = new UriSafeTokenGenerator();
$csrfStorage = new SessionTokenStorage($session);
$csrfManager = new CsrfTokenManager($csrfGenerator, $csrfStorage);
$factory = Forms::createFormFactoryBuilder()
->addExtension(new CsrfExtension($csrfManager))
->addExtension(new ValidatorExtension($validator))
->getFormFactory();
}
return $factory;
} | php | {
"resource": ""
} |
q265553 | FixturesLoader.loadFromIterator | test | private function loadFromIterator(\Iterator $iterator)
{
/* @var \SplFileInfo[] $iterator */
foreach ($iterator as $file) {
if ($file->getFilename() === 'fixtures.yml') {
$this->addFixture($file->getPathname());
}
}
} | php | {
"resource": ""
} |
q265554 | Url.resolveRelativeUrl | test | public function resolveRelativeUrl($url) {
try {
// return absolute url
return new static($url);
}
catch(UrlException $exception) {}
// anchor
if($url[0] === '#') {
return new static($this->getUrl(self::ALL - self::FRAGMENT) . $url);
}
// query
if($url[0] === '?') {
return new static($this->getUrl(self::ALL - self::FRAGMENT - self::QUERY) . $url);
}
// relative path from domain root
if($url[0] === '/') {
return new static($this->getUrl(self::ALL - self::FRAGMENT - self::QUERY - self::PATH) . substr($url, 1));
}
// relative path from current path
else {
$currentPath = $this->path ?: '/';
// cut last path fragment
if(substr($currentPath, -1) !== '/') {
$currentPath = substr($currentPath, 0, strrpos($currentPath, '/') + 1);
}
return new static($this->getUrl(self::ALL - self::FRAGMENT - self::QUERY - self::PATH) . $this->getCanonicalizedPath($currentPath . $url));
}
} | php | {
"resource": ""
} |
q265555 | Installer.install | test | public function install(InstalledRepositoryInterface $repo, PackageInterface $package) {
parent::install($repo, $package);
$strPackageName = $package->getName();
if (self::startsWith($strPackageName, 'qcubed/plugin')) {
$this->composerPluginInstall($package);
}
elseif (self::startsWith($strPackageName, 'qcubed/qcubed')) {
// updating the framework
$this->composerFrameworkInstall($package);
}
} | php | {
"resource": ""
} |
q265556 | Installer.composerPluginInstall | test | protected function composerPluginInstall ($package) {
require_once(($this->vendorDir ? $this->vendorDir . '/' : '') . 'qcubed/qcubed/qcubed.inc.php'); // get the configuration options so we can know where to put the plugin files
// recursively copy the contents of the install subdirectory in the plugin.
$strPluginDir = $this->getPackageBasePath($package);
$strInstallDir = $strPluginDir . '/install';
$strDestDir = __INCLUDES__ . '/plugins';
$this->filesystem->ensureDirectoryExists($strDestDir);
$this->io->write('Copying files from ' . $strInstallDir . ' to ' . $strDestDir);
self::copy_dir($strInstallDir, $strDestDir);
} | php | {
"resource": ""
} |
q265557 | Installer.composerFrameworkInstall | test | protected function composerFrameworkInstall ($package) {
$extra = $package->getExtra();
// recursively copy the contents of the install directory, providing each file is not there.
$strInstallDir = self::NormalizeNonPosixPath($this->getPackageBasePath($package)) . '/install/project';
$strDestDir = ($this->vendorDir ? $this->vendorDir . '/' : '') . '../project'; // try to find the default project location
$strDestDir = self::NormalizeNonPosixPath($strDestDir);
$this->io->write('Copying files from ' . $strInstallDir . ' to ' . $strDestDir);
self::copy_dir($strInstallDir, $strDestDir);
// Make sure particular directories are writable by the web server. These are listed in the extra section of the composer.json file.
// We are assuming that the first time installation is installed in a subdirectory of docroot.
$strInstallDir = self::NormalizeNonPosixPath(realpath(dirname($strDestDir)));
$strSubDirectory = '/' . basename($strInstallDir);
$strDocRoot = self::NormalizeNonPosixPath(realpath($strInstallDir . '/../'));
$strConfigDirectory = $strDestDir . '/includes/configuration';
$this->io->write('Updating permissions');
foreach ($extra['writePermission'] as $strDir) {
$strTargetDir = $strInstallDir . '/' . $strDir;
if(!file_exists($strTargetDir)){
mkdir($strTargetDir, 0777, true);
}
chmod ($strTargetDir, 0777);
}
// write configuration.inc.php only if it does not exists
if (!file_exists($strConfigDirectory . '/configuration.inc.php')) {
// fix up the configuration file
$strFile = file_get_contents($strConfigDirectory . '/configuration.inc.sample.php');
if ($strFile) {
$strFile = str_replace (['{docroot}', '{vd}', '{subdir}'], [$strDocRoot, '', $strSubDirectory], $strFile);
file_put_contents($strConfigDirectory . '/configuration.inc.php', $strFile);
}
}
} | php | {
"resource": ""
} |
q265558 | Installer.update | test | public function update(InstalledRepositoryInterface $repo, PackageInterface $initial, PackageInterface $target) {
parent::install($repo, $initial, $target);
$strPackageName = $target->getName();
if (self::startsWith($strPackageName, 'qcubed/plugin')) {
$this->composerPluginInstall($target);
}
elseif (self::startsWith($strPackageName, 'qcubed/qcubed')) {
// updating the framework
$this->composerFrameworkUpdate($target);
}
} | php | {
"resource": ""
} |
q265559 | Installer.composerFrameworkUpdate | test | protected function composerFrameworkUpdate ($package) {
require_once(($this->vendorDir ? $this->vendorDir . '/' : '') . 'qcubed/qcubed/qcubed.inc.php'); // get the configuration options so we can know where to put the plugin files
// recursively copy the contents of the install directory, providing each file is not there.
$strInstallDir = $this->getPackageBasePath($package) . '/install/project';
$strDestDir = __PROJECT__;
// copy_dir will not overwrite files, but will add any new stub files
$this->io->write('Copying files from ' . $strInstallDir . ' to ' . $strDestDir);
self::copy_dir($strInstallDir, $strDestDir);
} | php | {
"resource": ""
} |
q265560 | Installer.uninstall | test | public function uninstall(InstalledRepositoryInterface $repo, PackageInterface $package)
{
$strPackageName = $package->getName();
if (self::startsWith($strPackageName, 'qcubed/plugin')) {
$this->composerPluginUninstall($package);
}
parent::uninstall ($repo, $package);
} | php | {
"resource": ""
} |
q265561 | Installer.composerPluginUninstall | test | public function composerPluginUninstall (PackageInterface $package) {
require_once(($this->vendorDir ? $this->vendorDir . '/' : '') . 'qcubed/qcubed/qcubed.inc.php'); // get the configuration options so we can know where the plugin files are
// recursively delete the contents of the install directory, providing each file is there.
$strPluginDir = $this->getPackageBasePath($package) . '/install';
$strDestDir = __INCLUDES__ . '/plugins';
$this->io->write('Removing files from ' . $strPluginDir);
self::remove_matching_dir($strPluginDir, $strDestDir);
} | php | {
"resource": ""
} |
q265562 | Installer.remove_matching_dir | test | protected static function remove_matching_dir($src,$dst) {
if (!$dst || !$src || !is_dir($src) || !is_dir($dst)) return; // prevent deleting an entire disk by accidentally calling this with an empty string!
$dir = opendir($src);
while(false !== ( $file = readdir($dir)) ) {
if (( $file != '.' ) && ( $file != '..' )) {
if ( is_dir($src . '/' . $file) ) {
self::remove_dir($dst . '/' . $file);
}
else {
if (file_exists($dst . '/' . $file)) {
unlink($dst . '/' . $file);
}
}
}
}
closedir($dir);
} | php | {
"resource": ""
} |
q265563 | Installer.remove_dir | test | protected static function remove_dir($dst) {
if (!$dst || !is_dir($dst)) return; // prevent deleting an entire disk by accidentally calling this with an empty string!
$dir = opendir($dst);
while(false !== ( $file = readdir($dir)) ) {
if (( $file != '.' ) && ( $file != '..' )) {
if ( is_dir($dst . '/' . $file) ) {
self::remove_dir($dst . '/' . $file);
}
else {
unlink($dst . '/' . $file);
}
}
}
closedir($dir);
rmdir($dst);
} | php | {
"resource": ""
} |
q265564 | Column.setColors | test | public function setColors($textColor = null, $fillColor = null) {
// if the text color was specified
if ($textColor) {
// store it
$this->textColor = new Color($textColor);
// not set
} else {
// clear out the text color
$this->textColor = null;
}
// if the fill color was specified
if ($fillColor) {
// store it
$this->fillColor = new Color($fillColor);
// not set
} else {
// clear out the text color
$this->fillColor = null;
}
// chaining
return $this;
} | php | {
"resource": ""
} |
q265565 | Column.getTextArea | test | protected function getTextArea() {
// initialize the return value
$textArea = 0;
// if the width has a value (if it is calculated, it may not)
if ($this->width) {
// subtract the padding from the width
$textArea = $this->width - $this->rightPadding - $this->leftPadding;
}
// if it goes below zero
if ($textArea < 0) {
// make it zero
$textArea = 0;
}
return $textArea;
} | php | {
"resource": ""
} |
q265566 | Column.calculateWidth | test | public function calculateWidth($data, $markupDefinition = null) {
// if the width is not calculated, or the data is invalid
if (($this->calculateWidth === false) || !is_array($data) || (count($data) === 0)) {
// nothing to do, it is not a calculated width
return;
}
// initialize the array of sizes of each string
$sizes = [];
// reset the width
$this->width = null;
// if the header text was specified
if ($this->headerText) {
// add the length to the array of string lengths
$sizes[] = strlen($this->headerText);
}
// go through and create an array sizes
for ($i=0; $i<count($data); ++$i) {
// get the text (make it into a string)
$text = strval($data[$i]);
// if the markup definition was sent in
if ($markupDefinition) {
// strip out any markup symbols
$text = $markupDefinition->stripMarkupSymbols($text);
}
// add the size of this text to the array of sizes
$sizes[] = strlen($text);
}
// now get the highest value in the array of sizes and add the padding
$widestText = max($sizes) + $this->rightPadding + $this->leftPadding;
// if the maximum width is defined and the width hasn't already maxed out
if ($this->maximumWidth) {
// check to ensure the text length is less than or equal to the maximum width
if ($widestText <= $this->maximumWidth) {
// the width is now the newest text length
$this->width = $widestText;
} else {
// set the width to the maximum width (text will be truncated)
$this->width = $this->maximumWidth;
}
// there is no maximum width
} else {
// just set the width to that widest text
$this->width = $widestText;
}
} | php | {
"resource": ""
} |
q265567 | DateField.scopeGetByDateValue | test | public function scopeGetByDateValue($obQuery, $sField, $sDate, $sCondition = '=')
{
if(empty($sDate) || empty($sCondition) || empty($sField)) {
return $obQuery;
}
return $obQuery->where($sField, $sCondition, $sDate);
} | php | {
"resource": ""
} |
q265568 | DateField.getDateValue | test | public function getDateValue($sFieldName, $sFormat = 'd.m.Y')
{
if(empty($sFieldName) || empty($sFormat)) {
return null;
}
/** @var Carbon $obDate */
$obDate = $this->$sFieldName;
if(empty($obDate) || !$obDate instanceof Carbon) {
return $obDate;
}
return $obDate->format($sFormat);
} | php | {
"resource": ""
} |
q265569 | PolyfillTrait.castAttribute | test | protected function castAttribute($key, $value)
{
$type = $this->getCastType($key);
if (!empty($type) && !in_array($type, $this->originalCastTypes))
{
$method = 'as'.Str::studly($type);
if (method_exists($this, $method))
return call_user_func([$this, $method], $value, $key, $type);
}
return parent::castAttribute($key, $value);
} | php | {
"resource": ""
} |
q265570 | PolyfillTrait.attributesToArray | test | public function attributesToArray()
{
$data = parent::attributesToArray();
foreach ($this->getCasts() as $key => $type)
{
if (!empty($type) && !in_array($type, $this->originalCastTypes) && isset($data[$key]))
{
$method = Str::camel($type).'ToArray';
if (method_exists($this, $method))
$data[$key] = call_user_func([$this, $method], $data[$key], $key, $type);
}
}
return $data;
} | php | {
"resource": ""
} |
q265571 | TreeCollection.offsetSet | test | public function offsetSet($key, $value)
{
$value = $value instanceof TreeNode ? $value : new TreeNode($value);
if (is_null($key)) {
$this->items[] = $value;
} else {
$this->items[$key] = $value;
}
} | php | {
"resource": ""
} |
q265572 | ContainerProvider.get | test | public function get($name, array $options = [])
{
if (!isset($this->menuCollection[$name])) {
if (!isset($this->menuInfoCollection[$name])) {
throw new \InvalidArgumentException(\sprintf('The menu "%s" is not defined.', $name));
}
$menuInfo = $this->menuInfoCollection[$name];
$service = $menuInfo['id'];
$method = isset($menuInfo['method']) ? $menuInfo['method'] : 'getMenu';
$menu = $this->container->get($service)->$method($this->factory, $this->helper);
$event = new ConfigureMenuEvent($menu, $this->factory, $this->helper, $name);
$this->container->get('event_dispatcher')->dispatch('imatic_view.configure_menu.' . $name, $event);
$this->menuCollection[$name] = $menu;
}
return $this->menuCollection[$name];
} | php | {
"resource": ""
} |
q265573 | AddTrackingListener.onKernelResponse | test | public function onKernelResponse(FilterResponseEvent $event)
{
$config = [
'id' => $this->params['number'],
'accurateTrackBounce' => $this->params['accurateTrackBounce'], // показатель отказов: true | false | 10000 (ms)
'clickmap' => $this->params['clickmap'], // Включает карту кликов
'defer' => $this->params['defer'], // Не отправлять хит при инициализации счетчика
'enableAll' => $this->params['enableAll'], // Включает отслеживание внешних ссылок, карту кликов и точный показатель отказов
'onlyHttps' => $this->params['onlyHttps'], // true — данные в Метрику передаются только по https-протоколу;
'params' => $this->params['params'], // Параметры, передаваемые вместе с хитом
'trackHash' => true, // Включает отслеживание хеша в адресной строке браузера
'trackLinks' => true, // Включает отслеживание внешних ссылок
'type' => 0, // Тип счетчика. Для РСЯ равен 1
'ut' => 0, // Запрет отправки страниц на индексацию http://help.yandex.ru/metrika/code/stop-indexing.xml#stop-indexing
'webvisor' => true, // Включает Вебвизор
];
$htmlCode = $this->templating->render('keltanasYandexMetrikaBundle:Metrika:tracker.html.twig', [
'ya_tracking' => $this->params['number'],
'config' => array_filter($config),
'debug' => $this->debug,
]);
$event->getResponse()->setContent(str_replace(
'</body>',
$htmlCode . '</body>',
$event->getResponse()->getContent()
));
} | php | {
"resource": ""
} |
q265574 | YamlDefinitionLoader.getDefinitions | test | public function getDefinitions()
{
$content = $this->loadFile($this->fileName);
// empty file
if (null === $content) {
return [];
}
// imports
$definitions = $this->parseImports($content);
// parameters
if (isset($content['parameters'])) {
if (!is_array($content['parameters'])) {
throw new InvalidArgumentException(sprintf('The "parameters" key should contain an array in %s. Check your YAML syntax.', $this->fileName));
}
foreach ($content['parameters'] as $key => $value) {
$definitions[$key] = new ParameterDefinition($value);
//$this->container->setParameter($key, $this->resolveServices($value));
}
}
// services
$serviceDefinitions = $this->parseDefinitions($content);
$definitions = $definitions + $serviceDefinitions;
return $definitions;
} | php | {
"resource": ""
} |
q265575 | YamlDefinitionLoader.parseImports | test | private function parseImports($content)
{
if (!isset($content['imports'])) {
return [];
}
if (!is_array($content['imports'])) {
throw new InvalidArgumentException(sprintf('The "imports" key should contain an array in %s. Check your YAML syntax.', $this->fileName));
}
$additionalDefinitions = [];
foreach ($content['imports'] as $import) {
if (!is_array($import)) {
throw new InvalidArgumentException(sprintf('The values in the "imports" key should be arrays in %s. Check your YAML syntax.', $this->fileName));
}
if (isset($import['ignore_errors'])) {
throw new InvalidArgumentException(sprintf('The "ignore_errors" key is not supported in YamlDefinitionLoader. This is a Symfony specific syntax. Check your YAML syntax.', $this->fileName));
}
$importFileName = $import['resource'];
if (strpos($importFileName, '/') !== 0) {
$importFileName = dirname($this->fileName).'/'.$importFileName;
}
$yamlDefinitionLoader = new self($importFileName);
$newDefinitions = $yamlDefinitionLoader->getDefinitions();
$additionalDefinitions = $newDefinitions + $additionalDefinitions;
}
return $additionalDefinitions;
} | php | {
"resource": ""
} |
q265576 | YamlDefinitionLoader.parseDefinitions | test | private function parseDefinitions($content)
{
if (!isset($content['services'])) {
return [];
}
if (!is_array($content['services'])) {
throw new InvalidArgumentException(sprintf('The "services" key should contain an array in %s. Check your YAML syntax.', $this->fileName));
}
$definitions = [];
foreach ($content['services'] as $id => $service) {
$definitions[$id] = $this->parseDefinition($id, $service);
}
return $definitions;
} | php | {
"resource": ""
} |
q265577 | YamlDefinitionLoader.loadFile | test | protected function loadFile($file)
{
if (!stream_is_local($file)) {
throw new InvalidArgumentException(sprintf('This is not a local file "%s".', $file));
}
if (!is_readable($file)) {
throw new FileNotFoundException(sprintf('The file "%s" does not exist or is not readable.', $file));
}
$yamlParser = new Parser();
try {
$configuration = $yamlParser->parse(file_get_contents($file));
} catch (ParseException $e) {
throw new InvalidArgumentException(sprintf('The file "%s" does not contain valid YAML.', $file), 0, $e);
}
return $this->validate($configuration, $file);
} | php | {
"resource": ""
} |
q265578 | YamlDefinitionLoader.resolveServices | test | private function resolveServices($value)
{
if (is_array($value)) {
return array_map(array($this, 'resolveServices'), $value);
} elseif (is_string($value) && 0 === strpos($value, '@=')) {
throw new InvalidArgumentException('Expressions (starting by "@=") are not supported by YamlDefinitionLoader. This is a Symfony specific feature.');
} elseif (is_string($value) && 0 === strpos($value, '@')) {
if (0 === strpos($value, '@@')) {
return substr($value, 1);
} elseif (0 === strpos($value, '@?')) {
throw new InvalidArgumentException('Optional services (starting by "@?") are not supported by YamlDefinitionLoader. This is a Symfony specific feature.');
} else {
$value = substr($value, 1);
if ('=' === substr($value, -1)) {
throw new InvalidArgumentException('Non-strict services (ending with "=") are not supported by YamlDefinitionLoader. This is a Symfony specific feature.');
} else {
}
return new Reference($value);
}
} else {
return $value;
}
} | php | {
"resource": ""
} |
q265579 | AutoloadProvider.init | test | public function init(Autoload $loader, $loads = []){
$this->loader = $loader;
foreach ($loads['namespaces'] as $prefix => $namespace) {
$this->loader->addNamespace($prefix, ROOT . DIRECTORY_SEPARATOR . ltrim($namespace, '/'));
}
foreach ($loads['classes'] as $class => $path) {
$this->loader->addClass($class, ROOT . DIRECTORY_SEPARATOR . ltrim($path, '/'));
}
$this->loader->register();
} | php | {
"resource": ""
} |
q265580 | Encrypt.getApi | test | public function getApi()
{
if (is_null($this->api)) {
$this->api = new AES();
$this->api->setKey($this->getKey());
}
return $this->api;
} | php | {
"resource": ""
} |
q265581 | Utils.humanize | test | public static function humanize($bytes, $base = 1024)
{
if (empty($bytes)) {
return '0 B';
}
$class = min((int)log($bytes, $base), count(static::$siPrefix) - 1);
return sprintf('%1.2F %s', $bytes / pow($base, $class), static::$siPrefix[$class]);
} | php | {
"resource": ""
} |
q265582 | UnorderedList.setBullet | test | public function setBullet($str) {
// store the bullet, if it is null..
if (is_null($str)) {
// store the default bullet
$this->bullet = $this->defaultBullet;
// something was sent in
} else {
// store it
$this->bullet = $str;
}
return $this;
} | php | {
"resource": ""
} |
q265583 | Table.setColumnDefinition | test | public function setColumnDefinition($columnIndex, Column $column) {
// if the index is valid
if ($columnIndex < $this->columnCount) {
// copy the column information
$this->columnDefinitions[$columnIndex] = clone $column;
}
} | php | {
"resource": ""
} |
q265584 | Table.calcTotalWidth | test | protected function calcTotalWidth() {
$totalWidth = 0;
// go through all the widths
for ($w=0; $w<count($this->columnDefinitions); ++$w) {
// add the column's width
$totalWidth += $this->columnDefinitions[$w]->getWidth();
}
// return the total
return $totalWidth;
} | php | {
"resource": ""
} |
q265585 | Table.hasHeader | test | protected function hasHeader() {
// go through the column definitions
for ($i=0; $i<count($this->columnDefinitions); ++$i) {
// if one column has header text
if ($this->columnDefinitions[$i]->hasHeaderText()) {
// then there is a header
return true;
}
}
// none of the columns had header text
return false;
} | php | {
"resource": ""
} |
q265586 | Table.getHeaderText | test | protected function getHeaderText() {
$headers = [];
// go through the column definitions
for ($i=0; $i<count($this->columnDefinitions); ++$i) {
$next = $this->columnDefinitions[$i];
// if one column has header text
if ($this->columnDefinitions[$i]->hasHeaderText()) {
// then there is a header
$headers[] = $next->getHeaderText();
// there is no header
} else {
// put in a blank placeholder
$headers[] = "";
}
}
// none of the columns had header text
return $headers;
} | php | {
"resource": ""
} |
q265587 | Table.dataCheck | test | protected function dataCheck(&$data) {
// no need to go on, if there is no data
if (count($data) < 1 || !is_array($data)) {
// exit
return false;
}
// first check that there are enough Column definitions for the data supplied
for ($r=0; $r<count($data); ++$r) {
$rowColumnCount = count($data[$r]);
// if this row does not have enough columns, add them
if ($rowColumnCount > $this->columnCount) {
// add as many Columns as needed to handle this larger row
for ($i=$this->columnCount; $i<$rowColumnCount; ++$i) {
// add one default column
$this->columnDefinitions[] = new Column();
}
// update the column count to reflect this new size
$this->columnCount = $rowColumnCount;
}
}
// now, pad any row that doesn't have enough data to fill the columns
for ($r=0; $r<count($data); ++$r) {
// if this row does not have enough columns, add them
if (count($data[$r]) < $this->columnCount) {
// pad the array with empty space to fill out any columns not there
$data[$r] = array_pad($data[$r],$this->columnCount,"");
}
}
// we got past the hurdles, data is good
return true;
} | php | {
"resource": ""
} |
q265588 | Table.calculateWidths | test | protected function calculateWidths($data) {
// get the markup definition from the HTML object
$markupDefinition = $this->clio->getMarkupDefinition();
// go through and calculate any column widths that were not calculated
for ($column = 0; $column < $this->columnCount; ++$column) {
// get the column definition for this column
$columnDefinition = $this->columnDefinitions[$column];
// get the column of data
$columnData = array_column($data, $column);
// calculate it based on the widest text for that column
$columnDefinition->calculateWidth($columnData, $markupDefinition);
}
} | php | {
"resource": ""
} |
q265589 | Table.draw | test | public function draw($data) {
// if the data is sane, and the widths have been set (if not calculate them)
if ($this->dataCheck($data)) {
// calculate the widths
$this->calculateWidths($data);
// if at least one of the columns has header text
if ($this->hasHeader()) {
// bold and underscore for the title
$style = new Style();
$style->setBold()->setUnderscore();
$headers = $this->getHeaderText();
// draw the row of cells
$this->drawRow($headers, $style);
}
// go through each row of data
for ($row = 0; $row<count($data); ++$row) {
// draw the row of cells
$this->drawRow($data[$row], null);
}
}
} | php | {
"resource": ""
} |
q265590 | FileDriver.createSession | test | public function createSession(SessionManager $sessionManager, $userProfile = null)
{
list($sessionId, $fileHandle) = $this->createNewSessionFile();
$lockFileHandle = null;
if ($sessionManager->getLockMode() == SessionConfig::LOCK_ON_OPEN) {
$lockFileHandle = $this->acquireLock(
$sessionId,
$sessionManager->getSessionConfig()->getLockMilliSeconds(),
$sessionManager->getSessionConfig()->getMaxLockWaitTimeMilliseconds()
);
}
$existingProfiles = [];
if ($userProfile !== null) {
$existingProfiles[] = $userProfile;
}
$fileInfo = new FileInfo($lockFileHandle);
$this->save($sessionId, [], $existingProfiles, $fileInfo);
// fclose($fileHandle); umm.
return new FileSession(
$sessionId,
[],
$this,
$sessionManager,
$existingProfiles,
$fileInfo,
false
);
} | php | {
"resource": ""
} |
q265591 | FileDriver.createNewSessionFile | test | private function createNewSessionFile()
{
for ($count=0 ; $count<10 ; $count++) {
$sessionId = $this->idGenerator->generateSessionID();
$filename = $this->generateFilenameForDataFile($sessionId);
//TODO remove? - the user should create the directory themselves
$dirname = dirname($filename);
@mkdir($dirname);
//This only succeeds if the file doesn't already exist
$fileHandle = @fopen($filename, 'x+');
if ($fileHandle != false) {
return [$sessionId, $fileHandle];
}
};
throw new AsmException(
"Failed to open a new session file with random name.",
AsmException::ID_CLASH
);
} | php | {
"resource": ""
} |
q265592 | FileDriver.save | test | public function save($sessionId, $data, $existingProfiles, FileInfo $fileInfo)
{
$rawData = [];
$rawData['data'] = $data;
$rawData['profiles'] = $existingProfiles;
$dataString = $this->serializer->serialize($rawData);
$filename = $this->generateFilenameForDataFile($sessionId);
$tempFilename = tempnam(dirname($filename), basename($filename));
$writeResult = @file_put_contents($tempFilename, $dataString);
if ($writeResult === false) {
throw new AsmException(
"Failed to write session data.",
AsmException::IO_ERROR
);
}
$tempLockFileHandle = null;
if ($fileInfo->lockFileHandle) {
$this->validateLock($sessionId, $fileInfo);
}
else {
$tempLockFileHandle = $this->acquireLock(
$sessionId,
5000,
1000
);
}
//We have the lock - it's safe to replace the datafile
$renamed = rename($tempFilename, $filename);
if ($tempLockFileHandle) {
fclose($tempLockFileHandle);
}
if (!$renamed) {
throw new AsmException(
"Failed to save session data during rename of file",
AsmException::IO_ERROR
);
}
} | php | {
"resource": ""
} |
q265593 | FileDriver.acquireLock | test | public function acquireLock($sessionId, $lockTimeMS, $acquireTimeoutMS)
{
// Get the time in MS
$currentTime = microtime(true);
$giveUpTime = $currentTime + ($acquireTimeoutMS * 0.001);
$lockFilename = $this->generateFilenameForLockFile($sessionId);
do {
//Re-open the lock file every loop, to prevent issues where another
//process deletes it.
$fileHandle = fopen($lockFilename, 'c+');
//'c+' means "Open the file for writing only. If the file does not exist,
// it is created. If it exists, it is neither truncated (as opposed to 'w'),
// nor the call to this function fails (as is the case with 'x').
$locked = flock($fileHandle, LOCK_EX|LOCK_NB);
if ($locked) {
//$touchTime = time() + intval(ceil($lockTimeMS / 1000));
$expireTime = microtime(true) + ($lockTimeMS * 0.0001);
file_put_contents(
$lockFilename,
sprintf("%f", $expireTime)
);
//touch($lockFilename, $touchTime);
return $fileHandle;
}
//We did not acquire a lock - check to see if the lock has expired
$contents = file_get_contents($lockFilename);
$existingExpireTime = floatval($contents);
// TODO - we could do a basic sanity test on the lock data
// however, what we be the correct action to take?
// if ($existingExpireTime < 1447040641 ||
// $existingExpireTime > 2551578313) {
// //lock contents are rubbish
// //TODO - decide what to do.
// }
if (microtime(true) > $existingExpireTime) {
unlink($lockFilename);
}
else {
// sleep 1ms to avoid churning CPU
usleep(1000);
}
} while($giveUpTime > microtime(true));
throw new FailedToAcquireLockException(
"FileDriver failed to acquire lock."
);
} | php | {
"resource": ""
} |
q265594 | SectionFormTwigExtension.sectionForm | test | public function sectionForm(
string $forHandle,
array $sectionFormOptions = []
): FormView {
$sectionFormOptions = SectionFormOptions::fromArray($sectionFormOptions);
$form = $this->form->buildFormForSection(
$forHandle,
$this->requestStack,
$sectionFormOptions
);
$form->handleRequest();
if ($form->isSubmitted() &&
$form->isValid()
) {
$data = $form->getData();
$this->createSection->save($data);
try {
$redirect = $sectionFormOptions->getRedirect();
} catch (\Exception $exception) {
$redirect = '/';
}
header('Location: ' . $redirect);
exit;
}
return $form->createView();
} | php | {
"resource": ""
} |
q265595 | ReflectionProperty.factory | test | public static function factory($class, $property = null)
{
if (is_object($class))
$class = get_class($class);
$class = (string)$class;
if (!isset(self::$properties[$class])) {
$classReflection = new \ReflectionClass($class);
$properties = $classReflection->getProperties();
self::$properties[$class] = array();
foreach ($properties as $propertyReflection) {
if ($propertyReflection->class != $class) {
self::$properties[$class][$propertyReflection->name] = self::factory($propertyReflection->class, $propertyReflection->name);
} else {
self::$properties[$class][$propertyReflection->name] = new self($propertyReflection->class, $propertyReflection->name);
self::$properties[$class][$propertyReflection->name]->setAccessible(true);
}
}
}
if (isset($property)) {
if (!isset(self::$properties[$class][$property])) {
self::$properties[$class][$property] = new self($class, $property);
self::$properties[$class][$property]->setAccessible(true);
}
return self::$properties[$class][$property];
} else
return array_values(self::$properties[$class]);
} | php | {
"resource": ""
} |
q265596 | CommandProvider.getFacts | test | public function getFacts()
{
try {
$output = $this->runCommand($this->cmd);
if ($this->as_json) {
$json = json_decode($output, true);
if (is_null($json)) {
return array();
}
return $json;
} else {
return $this->parseFacts($output);
}
} catch (\Exception $e) {
return array();
}
} | php | {
"resource": ""
} |
q265597 | CommandProvider.parseFacts | test | protected function parseFacts($facts_string)
{
$facts = array();
foreach (explode(PHP_EOL, $facts_string) as $line) {
if (empty($line)) {
continue;
}
list($key, $value) = explode('=', $line, 2);
$facts[$key] = $value;
}
return $facts;
} | php | {
"resource": ""
} |
q265598 | ActiveRecordModel.findById | test | public function findById($id = null)
{
$id = $id ?: $this->{$this->tableIdColumn};
return $this->findWhere("{$this->tableIdColumn} = ?", $id);
} | php | {
"resource": ""
} |
q265599 | ActiveRecordModel.findWhere | test | public function findWhere($where, $value)
{
$this->checkDb();
$params = is_array($value) ? $value : [$value];
$this->db->connect()
->select()
->from($this ->tableName)
->where($where)
->execute($params)
->fetchInto($this);
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.