_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q250200
FMSummernoteExtension.prepareArrayParameter
validation
private function prepareArrayParameter($name) { if (isset($this->parameters[$name])) { $parameterArray = $this->parameters[$name]; $count = count($parameterArray); $str = "['".$parameterArray[0]."'"; for ($i = 1; $i < $count; ++$i) { $str .= ", '".$parameterArray[$i]."'"; } $str .= ']'; return $str; } }
php
{ "resource": "" }
q250201
OpenStreetMapObject.sendRequest
validation
public function sendRequest($path, $method = 'GET', $headers = array(), $data = '') { // Send the request. switch ($method) { case 'GET': $response = $this->client->get($path, $headers); break; case 'POST': $response = $this->client->post($path, $data, $headers); break; } // Validate the response code. if ($response->code != 200) { $error = htmlspecialchars($response->body); throw new \DomainException($error, $response->code); } return simplexml_load_string($response->body); }
php
{ "resource": "" }
q250202
CSVTable.fromMinkResponse
validation
public static function fromMinkResponse(\Behat\Mink\Session $session) { return self::newInstance()->makeMinkResponseCSVTableParser()->parse($session); }
php
{ "resource": "" }
q250203
FilterUtilHelper.extractArrayCriteria
validation
private static function extractArrayCriteria($key, array $criteria) { if (!empty($criteria[$key])) { return array($criteria[$key]); } if (!empty($criteria[$key.'s'])) { return $criteria[$key.'s']; } return array(); }
php
{ "resource": "" }
q250204
FilterUtilHelper.extractDateCriteria
validation
private static function extractDateCriteria($key, array $criteria) { $date = (!empty($criteria[$key])) ? $criteria[$key] : null; if (is_string($date)) { $date = \DateTime::createFromFormat('Y-m-d', $date); } if (false === $date) { throw new InvalidArgumentException(sprintf('Invalid date/time format provided "%s", expected "%s", or instance of \DateTime class.', $criteria[$key], 'Y-m-d')); } return $date; }
php
{ "resource": "" }
q250205
FilterUtilHelper.matchesArrayCriteria
validation
private static function matchesArrayCriteria($key, $object, array $criteria) { $criteria = self::extractArrayCriteria($key, $criteria); if (count($criteria) === 0) { return true; } $getter = sprintf('get%s', ucfirst($key)); if (!method_exists($object, $getter)) { throw new RuntimeException(sprintf('Object instance of "%s" does not have required getter "%s" to be used for filtering.', get_class($object), $getter)); } return in_array($object->{$getter}(), $criteria, true); }
php
{ "resource": "" }
q250206
ExtendedPdoAdapter.rewriteCountQuery
validation
public function rewriteCountQuery($query) { if (\preg_match('/^\s*SELECT\s+\bDISTINCT\b/is', $query) || \preg_match('/\s+GROUP\s+BY\s+/is', $query)) { return ''; } $openParenthesis = '(?:\()'; $closeParenthesis = '(?:\))'; $subQueryInSelect = $openParenthesis . '.*\bFROM\b.*' . $closeParenthesis; $pattern = '/(?:.*' . $subQueryInSelect . '.*)\bFROM\b\s+/Uims'; if (\preg_match($pattern, $query)) { return ''; } $subQueryWithLimitOrder = $openParenthesis . '.*\b(LIMIT|ORDER)\b.*' . $closeParenthesis; $pattern = '/.*\bFROM\b.*(?:.*' . $subQueryWithLimitOrder . '.*).*/Uims'; if (\preg_match($pattern, $query)) { return ''; } $queryCount = \preg_replace('/(?:.*)\bFROM\b\s+/Uims', 'SELECT COUNT(*) FROM ', $query, 1); list($queryCount) = \preg_split('/\s+ORDER\s+BY\s+/is', $queryCount); list($queryCount) = \preg_split('/\bLIMIT\b/is', $queryCount); return \trim($queryCount); }
php
{ "resource": "" }
q250207
CurrencyCodeUtil.exists
validation
public static function exists($currencyCode) { $currencyCode = trim(strtoupper($currencyCode)); return array_key_exists($currencyCode, self::$codes); }
php
{ "resource": "" }
q250208
CurrencyCodeUtil.clean
validation
public static function clean($currencyCode) { $clean = trim(strtoupper($currencyCode)); if (!self::exists($clean)) { throw new UnknownCurrencyCodeException(sprintf('Unknown currency code "%s".', $currencyCode)); } return $clean; }
php
{ "resource": "" }
q250209
FileRepository.load
validation
protected function load() { $this->rates = array(); $this->latest = array(); $handle = fopen($this->pathToFile, 'rb'); if (!$handle) { throw new RuntimeException(sprintf('Error opening file on path "%s".', $this->pathToFile)); // @codeCoverageIgnore } while (($line = fgets($handle)) !== false) { $rate = $this->fromJson($line); $this->rates[$this->getRateKey($rate->getCurrencyCode(), $rate->getDate(), $rate->getRateType(), $rate->getSourceName())] = $rate; $latestKey = sprintf('%s_%s_%s', $rate->getCurrencyCode(), $rate->getRateType(), $rate->getSourceName()); if (!isset($this->latest[$latestKey]) || ($this->latest[$latestKey]->getDate() < $rate->getDate())) { $this->latest[$latestKey] = $rate; } } fclose($handle); return $this->rates; }
php
{ "resource": "" }
q250210
FileRepository.initialize
validation
protected function initialize() { /** @noinspection MkdirRaceConditionInspection */ if (!file_exists(dirname($this->pathToFile)) && !mkdir(dirname($this->pathToFile), 0777, true)) { throw new RuntimeException(sprintf('Could not create storage file on path "%s".', $this->pathToFile)); } if (!file_exists($this->pathToFile) && !(touch($this->pathToFile) && chmod($this->pathToFile, 0777))) { throw new RuntimeException(sprintf('Could not create storage file on path "%s".', $this->pathToFile)); } if (!is_readable($this->pathToFile)) { throw new RuntimeException(sprintf('File on path "%s" for storing rates must be readable.', $this->pathToFile)); } if (!is_writable($this->pathToFile)) { throw new RuntimeException(sprintf('File on path "%s" for storing rates must be writeable.', $this->pathToFile)); } }
php
{ "resource": "" }
q250211
FileRepository.toJson
validation
protected function toJson(RateInterface $rate) { return json_encode(array( 'sourceName' => $rate->getSourceName(), 'value' => $rate->getValue(), 'currencyCode' => $rate->getCurrencyCode(), 'rateType' => $rate->getRateType(), 'date' => $rate->getDate()->format(\DateTime::ATOM), 'baseCurrencyCode' => $rate->getBaseCurrencyCode(), 'createdAt' => $rate->getCreatedAt()->format(\DateTime::ATOM), 'modifiedAt' => $rate->getModifiedAt()->format(\DateTime::ATOM), )); }
php
{ "resource": "" }
q250212
FileRepository.fromJson
validation
protected function fromJson($json) { $data = json_decode($json, true); return new Rate( $data['sourceName'], (float) $data['value'], $data['currencyCode'], $data['rateType'], \DateTime::createFromFormat(\DateTime::ATOM, $data['date']), $data['baseCurrencyCode'], \DateTime::createFromFormat(\DateTime::ATOM, $data['createdAt']), \DateTime::createFromFormat(\DateTime::ATOM, $data['modifiedAt']) ); }
php
{ "resource": "" }
q250213
FileRepository.paginate
validation
protected function paginate(array $rates, $criteria) { if (!array_key_exists('offset', $criteria) && !array_key_exists('limit', $criteria)) { return $rates; } $range = array(); $offset = array_key_exists('offset', $criteria) ? $criteria['offset'] : 0; $limit = min((array_key_exists('limit', $criteria) ? $criteria['limit'] : count($rates)) + $offset, count($rates)); for ($i = $offset; $i < $limit; $i++) { $range[] = $rates[$i]; } return $range; }
php
{ "resource": "" }
q250214
SourcesRegistry.filter
validation
private function filter($sources, array $filters = array()) { $result = array(); foreach ($sources as $source) { if (SourceFilterUtil::matches($source, $filters)) { $result[] = $source; } } return $result; }
php
{ "resource": "" }
q250215
Configuration.setOutputFormat
validation
public function setOutputFormat($format) { $output = array('xml', 'html', 'text', 'text-main'); if (!in_array($format, $output)) { throw new \InvalidArgumentException(sprintf( 'Available output format: %s', implode(', ', $output) )); } $this->outputFormat = $format; return $this; }
php
{ "resource": "" }
q250216
CSVStreamTableParser.parse
validation
public function parse($stream) { if ( ! ($this->isValidStream($stream))) { throw new \InvalidArgumentException(__METHOD__.' requires a valid stream resource'); } $original_position = \ftell($stream); try { \fseek($stream, 0); return new PaddedTableNode($this->readCSVRows($stream)); } finally { \fseek($stream, $original_position); } }
php
{ "resource": "" }
q250217
ExchangeRateException.typeOf
validation
public static function typeOf($arg) { if (null === $arg) { return 'NULL'; } if (is_object($arg)) { return get_class($arg); } return gettype($arg); }
php
{ "resource": "" }
q250218
Wrapper.setParameter
validation
public function setParameter($name, $value) { if (!isset($ref)) { $ref = new \ReflectionClass($this->config); } $function = sprintf('set%s', ucfirst($name)); if (!$ref->hasMethod($function)) { throw new \InvalidArgumentException(sprintf( 'The function "%s" does not exists on configuration', $name )); } $this->config->$function($value); return $this; }
php
{ "resource": "" }
q250219
DoctrineDbalRepository.getRateKey
validation
protected function getRateKey($currencyCode, $date, $rateType, $sourceName) { return str_replace( ['%currency_code%', '%date%', '%rate_type%', '%source_name%'], [$currencyCode, $date->format('Y-m-d'), $rateType, $sourceName], '%currency_code%_%date%_%rate_type%_%source_name%' ); }
php
{ "resource": "" }
q250220
DoctrineDbalRepository.initialize
validation
protected function initialize() { if ($this->connection->getSchemaManager()->tablesExist([$this->tableName])) { return; // @codeCoverageIgnore } $schema = new Schema(); $table = $schema->createTable($this->tableName); $table->addColumn('source_name', 'string', ['length' => 255]); $table->addColumn('rate_value', 'float', ['precision' => 10, 'scale' => 4]); $table->addColumn('currency_code', 'string', ['length' => 3]); $table->addColumn('rate_type', 'string', ['length' => 255]); $table->addColumn('rate_date', 'date', []); $table->addColumn('base_currency_code', 'string', ['length' => 3]); $table->addColumn('created_at', 'datetime', []); $table->addColumn('modified_at', 'datetime', []); $table->setPrimaryKey(['currency_code', 'rate_date', 'rate_type', 'source_name']); $this->connection->exec($schema->toSql($this->connection->getDatabasePlatform())[0]); }
php
{ "resource": "" }
q250221
DoctrineDbalRepository.buildRateFromTableRowData
validation
private function buildRateFromTableRowData(array $row) { return new Rate( $row['source_name'], (float)$row['rate_value'], $row['currency_code'], $row['rate_type'], \DateTime::createFromFormat('Y-m-d', $row['rate_date']), $row['base_currency_code'], \DateTime::createFromFormat('Y-m-d H:i:s', $row['created_at']), \DateTime::createFromFormat('Y-m-d H:i:s', $row['modified_at']) ); }
php
{ "resource": "" }
q250222
RateFilterUtil.matchesDateCriteria
validation
private static function matchesDateCriteria($key, RateInterface $rate, array $criteria) { $date = self::extractDateCriteria($key, $criteria); if ($date === null) { return true; } if ($key === 'dateFrom') { $rateDate = new \DateTime($rate->getDate()->format(\DateTime::ATOM)); $rateDate->setTime(23, 59, 59); return $date <= $rateDate; } if ($key === 'dateTo') { $rateDate = new \DateTime($rate->getDate()->format(\DateTime::ATOM)); $rateDate->setTime(0, 0, 0); return $date >= $rateDate; } return $date->format('Y-m-d') === $rate->getDate()->format('Y-m-d'); }
php
{ "resource": "" }
q250223
RatesConfigurationRegistry.filter
validation
private function filter($configurations, array $criteria) { $result = array(); /** * @var Configuration $configuration */ foreach ($configurations as $configuration) { if (ConfigurationFilterUtil::matches($configuration, $criteria)) { $result[] = $configuration; } } return $result; }
php
{ "resource": "" }
q250224
AssertTable.isSame
validation
public function isSame(TableNode $expected, TableNode $actual, $message = NULL) { $this->doAssert( 'Failed asserting that two tables were identical: ', [], $expected, $actual, $message ); }
php
{ "resource": "" }
q250225
AssertTable.isEqual
validation
public function isEqual(TableNode $expected, TableNode $actual, $message = NULL) { $this->doAssert( 'Failed asserting that two tables were equivalent: ', ['ignoreColumnSequence' => TRUE], $expected, $actual, $message ); }
php
{ "resource": "" }
q250226
AssertTable.isComparable
validation
public function isComparable( TableNode $expected, TableNode $actual, array $diff_options, $message = NULL ) { $this->doAssert( 'Failed comparing two tables: ', $diff_options, $expected, $actual, $message ); }
php
{ "resource": "" }
q250227
AbstractTable.get_columns
validation
public function get_columns() { return array( 'id' => new IntegerBased( 'BIGINT', 'id', array( 'NOT NULL', 'auto_increment' ), array( 20 ) ), 'message' => new StringBased( 'VARCHAR', 'message', array(), array( 255 ) ), 'level' => new StringBased( 'VARCHAR', 'level', array(), array( 20 ) ), 'lgroup' => new StringBased( 'VARCHAR', 'lgroup', array(), array( 20 ) ), 'time' => new DateTime( 'time' ), 'user' => new ForeignUser( 'user' ), 'ip' => new StringBased( 'VARCHAR', 'ip', array(), array( 45 ) ), 'exception' => new StringBased( 'VARCHAR', 'exception', array(), array( 255 ) ), 'trace' => new StringBased( 'LONGTEXT', 'trace' ), 'context' => new StringBased( 'LONGTEXT', 'context' ), ); }
php
{ "resource": "" }
q250228
HttpStatus.parseStatus
validation
public static function parseStatus($statusLine): HttpStatus { list ($proto, $code) = sscanf($statusLine, "%s %d %s"); return new HttpStatus($code, $proto); }
php
{ "resource": "" }
q250229
HttpStatus.toStatusLine
validation
public function toStatusLine(): string { return sprintf("%s %d %s", $this->proto, $this->code, self::getStatus($this->code)); }
php
{ "resource": "" }
q250230
UI.getTemplate
validation
public function getTemplate($data_type, $type) { $options = (array) $this->config->getType($data_type, $type); return new UI\Template($data_type, $type, $options); }
php
{ "resource": "" }
q250231
UI.getTemplates
validation
public function getTemplates() { $templates = array(); $types = $this->config->getTypes(); foreach ($types as $type => $type_options) { foreach ($type_options as $subtype => $subtype_options) { $templates[$type][$subtype] = (array) $subtype_options; } } return $templates; }
php
{ "resource": "" }
q250232
EntityFactory.build
validation
public function build($attributes = null) { if ($attributes instanceof \ElggEntity) { return $attributes; } if (is_numeric($attributes)) { return $this->get($attributes); } $attributes = (array) $attributes; if (!empty($attributes['guid'])) { return $this->get($attributes['guid']); } $type = elgg_extract('type', $attributes, 'object'); $subtype = elgg_extract('subtype', $attributes, ELGG_ENTITIES_ANY_VALUE); unset($attributes['type']); unset($attributes['subtype']); $class = get_subtype_class($type, $subtype); if (class_exists($class)) { $entity = new $class(); } else { switch ($type) { case 'object' : $entity = new \ElggObject(); $entity->subtype = $subtype; break; case 'user' : $entity = new \ElggUser(); $entity->subtype = $subtype; break; case 'group' : $entity = new \ElggGroup(); $entity->subtype = $subtype; break; } } foreach ($attributes as $key => $value) { if (in_array($key, $this->getAttributeNames($entity))) { $entity->$key = $value; } } return $entity; }
php
{ "resource": "" }
q250233
EntityFactory.getAttributeNames
validation
public function getAttributeNames($entity) { if (!$entity instanceof \ElggEntity) { return array(); } $default = array( 'guid', 'type', 'subtype', 'owner_guid', 'container_guid', 'site_guid', 'access_id', 'time_created', 'time_updated', 'last_action', 'enabled', ); switch ($entity->getType()) { case 'user'; $attributes = array( 'name', 'username', 'email', 'language', 'banned', 'admin', 'password', 'salt' ); break; case 'group' : $attributes = array( 'name', 'description', ); break; case 'object' : $attributes = array( 'title', 'description', ); break; } return array_merge($default, $attributes); }
php
{ "resource": "" }
q250234
ArtificialIntelligence.expecting
validation
public function expecting() { $possibilities = count($this->samples); $orderedByOccurance = array_count_values($this->samples); array_multisort($orderedByOccurance, SORT_DESC); $probabilities = []; foreach ($orderedByOccurance as $item => $value) { $probabilities[$item] = $value / $possibilities; } return $probabilities; }
php
{ "resource": "" }
q250235
Session.update
validation
private function update() { if (null !== $this->namespace) { $_SESSION[$this->namespace] = $this->sessionData; } else { $_SESSION = $this->sessionData; } }
php
{ "resource": "" }
q250236
RamlConverter.addActions
validation
protected function addActions(SymfonyController $controller, Resource $resource, $chainName = '') { $actions = array(); $chainName = $chainName . '_' . strtolower(str_replace(array('{', '}'), '', $resource->getDisplayName())); foreach ($resource->getMethods() as $method) { $actionName = strtolower($method->getType()) . str_replace(' ', '', ucwords(str_replace('_', ' ', $chainName))) . 'Action'; $route = new SymfonyRoute($resource->getUri(), strtolower($method->getType() . $chainName)); $action = new SymfonyAction($actionName, $route, $method->getType(), $method->getDescription()); preg_match_all('/\{[a-zA-Z]+\}/', $resource->getUri(), $parameters); foreach ($parameters[0] as $parameter) { $action->addParameter(substr($parameter, 1, strlen($parameter) - 2)); } if ($method->getResponses()) { foreach ($method->getResponses() as $code => $response) { $headers = array(); foreach ($response->getHeaders() as $key => $value) { if (isset($value['required']) && $value['required']) { $headers[$key] = isset($value['example']) ? $value['example'] : ''; } } $_response = new SymfonyResponse($code, $headers); foreach ($this->config['allowed_response_types'] as $allowedResponsetype) { if (null !== $example = $response->getExampleByType($allowedResponsetype)) { $_response->addContent(new SymfonyResponseContent($allowedResponsetype, str_replace(array("\r\n", "\n", "\r", "\t", " "), '', $example))); } } $action->addResponse($_response); } } $controller->addAction($action); } foreach ($resource->getResources() as $subresource) { $this->addActions($controller, $subresource, $chainName); } }
php
{ "resource": "" }
q250237
RamlConverter.buildNamespace
validation
protected function buildNamespace(ApiDefinition $definition, $namespace) { if ($this->config['version_in_namespace'] && $definition->getVersion()) { $namespace .= '\\' . preg_replace( array('/(^[0-9])/', '/[^a-zA-Z0-9]/'), array('Version\1', '_'), $definition->getVersion() ); } return $namespace; }
php
{ "resource": "" }
q250238
Directory.isEmpty
validation
public function isEmpty($filter = null): bool { if (! $this->exists()) { throw new DirectoryException("Directory {dir} does not exist", array( 'dir' => $this->path )); } $iter = new \DirectoryIterator($this->path); while ($iter->valid()) { if (! $iter->isDot() && ($filter === null || ! preg_match("/$filter/", $iter->getFilename()))) { return false; } $iter->next(); } return true; }
php
{ "resource": "" }
q250239
Directory.exists
validation
public function exists(): bool { if (! file_exists($this->path)) { return false; } if (! is_dir($this->path)) { throw new DirectoryException("Entry {path} exists, but it is not a directory!", array( 'path' => $this->path )); } return true; }
php
{ "resource": "" }
q250240
Directory.fileExists
validation
public function fileExists($fileName): bool { if (! $this->exists()) { return false; } $file = sprintf("%s/%s", $this->path, $fileName); return file_exists($file); }
php
{ "resource": "" }
q250241
Directory.fixDirectorySeparator
validation
private function fixDirectorySeparator($path): string { $path = str_replace("\\", DIRECTORY_SEPARATOR, $path); $path = str_replace("/", DIRECTORY_SEPARATOR, $path); return $path; }
php
{ "resource": "" }
q250242
ListTable.column_user
validation
public function column_user( AbstractLog $item ) { $user = $item->get_user(); if ( empty( $user ) ) { echo '-'; } else { echo $user->display_name; } }
php
{ "resource": "" }
q250243
ListTable.column_time
validation
public function column_time( AbstractLog $item ) { $time = $item->get_time(); if ( empty( $time ) ) { echo '-'; } else { echo $time->format( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ) ); } }
php
{ "resource": "" }
q250244
ListTable.extra_tablenav
validation
protected function extra_tablenav( $which ) { if ( $which !== 'top' ) { return; } $this->months_dropdown( '' ); $selected = isset( $_GET['level'] ) ? $_GET['level'] : ''; ?> <label for="filter-by-level" class="screen-reader-text"> <?php echo $this->translations['levelFilterLabel']; ?> </label> <select name="level" id="filter-by-level"> <option value=""><?php echo $this->translations['allLevels']; ?></option> <?php foreach ( $this->get_levels() as $level => $label ): ?> <option value="<?php echo esc_attr( $level ); ?>" <?php selected( $selected, $level ); ?>> <?php echo $label; ?> </option> <?php endforeach; ?> </select> <?php submit_button( $this->translations['filter'], 'button', 'filter_action', false ); }
php
{ "resource": "" }
q250245
ListTable.months_dropdown
validation
protected function months_dropdown( $post_type ) { global $wpdb, $wp_locale; $tn = $this->table->get_table_name( $wpdb ); $months = $wpdb->get_results( " SELECT DISTINCT YEAR( time ) AS year, MONTH( time ) AS month FROM $tn ORDER BY time DESC " ); $month_count = count( $months ); if ( ! $month_count || ( 1 == $month_count && 0 == $months[0]->month ) ) { return; } $m = isset( $_GET['m'] ) ? (int) $_GET['m'] : 0; ?> <label for="filter-by-date" class="screen-reader-text"><?php _e( 'Filter by date' ); ?></label> <select name="m" id="filter-by-date"> <option<?php selected( $m, 0 ); ?> value="0"><?php _e( 'All dates' ); ?></option> <?php foreach ( $months as $arc_row ) { if ( 0 == $arc_row->year ) { continue; } $month = zeroise( $arc_row->month, 2 ); $year = $arc_row->year; printf( "<option %s value='%s'>%s</option>\n", selected( $m, $year . $month, false ), esc_attr( $arc_row->year . $month ), /* translators: 1: month name, 2: 4-digit year */ sprintf( __( '%1$s %2$d' ), $wp_locale->get_month( $month ), $year ) ); } ?> </select> <?php }
php
{ "resource": "" }
q250246
ListTable.get_levels
validation
protected function get_levels() { return array( LogLevel::EMERGENCY => 'Emergency', LogLevel::ALERT => 'Alert', LogLevel::CRITICAL => 'Critical', LogLevel::ERROR => 'Error', LogLevel::WARNING => 'Warning', LogLevel::NOTICE => 'Notice', LogLevel::INFO => 'Info', LogLevel::DEBUG => 'Debug' ); }
php
{ "resource": "" }
q250247
FieldFactory.build
validation
public function build($options = array()) { if (is_string($options)) { $options = array( 'type' => $options, ); } else if (!is_array($options)) { $options = array( 'type' => 'text', ); } if (empty($options['type'])) { $options['type'] = 'text'; } if (empty($options['data_type'])) { $options['data_type'] = 'metadata'; } $defaults = (array) $this->config->getType($options['data_type'], $options['type']); $options = array_merge($defaults, $options); $classname = elgg_extract('class_name', $options); if (class_exists($classname)) { return new $classname($options); } return false; }
php
{ "resource": "" }
q250248
FieldCollection.sort
validation
public function sort() { $this->uasort(function($a, $b) { $priority_a = (int) $a->get('priority') ? : 500; $priority_b = (int) $b->get('priority') ? : 500; if ($priority_a == $priority_b) { return 0; } return ($priority_a < $priority_b) ? -1 : 1; }); return $this; }
php
{ "resource": "" }
q250249
Column.prepareColumn
validation
private function prepareColumn(Row $row): string { $nullable = $row->Null === 'YES'; if ($row->Default === null && !$nullable) { $default = ' NOT null'; } elseif ($row->Default === null && $nullable) { $default = ' DEFAULT null'; } else { $default = ($nullable ? '' : ' NOT null') . " DEFAULT '{$row->Default}'"; } if (!empty($row->Collation)) { $collate = ' COLLATE ' . $row->Collation; } else { $collate = ''; } if ($row->Extra === 'auto_increment') { $autoIncrement = ' AUTO_INCREMENT'; } else { $autoIncrement = ''; } return "`{$row->Field}` " . $row->Type . $collate . $default . $autoIncrement; }
php
{ "resource": "" }
q250250
Column.decimal
validation
public function decimal(int $total, int $decimal): self { $this->type = 'decimal(' . $total . ',' . $decimal . ')'; return $this; }
php
{ "resource": "" }
q250251
Column.char
validation
public function char(int $size = 36, string $charset = null): self { $this->type = 'char(' . $size . ')' . $this->stringOptions($charset); return $this; }
php
{ "resource": "" }
q250252
Column.tinytext
validation
public function tinytext(string $charset = null): self { $this->type = 'tinytext' . $this->stringOptions($charset); return $this; }
php
{ "resource": "" }
q250253
Column.text
validation
public function text(string $charset = null): self { $this->type = 'text' . $this->stringOptions($charset); return $this; }
php
{ "resource": "" }
q250254
Column.mediumtext
validation
public function mediumtext(string $charset = null): self { $this->type = 'mediumtext' . $this->stringOptions($charset); return $this; }
php
{ "resource": "" }
q250255
Column.longtext
validation
public function longtext(string $charset = null): self { $this->type = 'longtext' . $this->stringOptions($charset); return $this; }
php
{ "resource": "" }
q250256
ThemeHelper.getRoot
validation
function getRoot() { $sm = $this->sl->getServiceLocator(); $event = $sm->get('Application') ->getMvcEvent(); return $event->getViewModel(); }
php
{ "resource": "" }
q250257
UserController.markAllNotificationsAsRead
validation
public function markAllNotificationsAsRead() { /** @var \Unite\UnisysApi\Models\User $object */ $object = Auth::user(); $object->unreadNotifications->markAsRead(); \Cache::tags('response')->flush(); return $this->successJsonResponse(); }
php
{ "resource": "" }
q250258
Linguistics.getWords
validation
public function getWords($string, $minLength = null) { $tokenizer = new Whitespace(); $words = $tokenizer->tokenize($string); if (!is_null($minLength)) { foreach ($words as $key => $word) { if (strlen($word) <= $minLength) { unset($words[$key]); } } } return array_values($words); }
php
{ "resource": "" }
q250259
Linguistics.getActionWords
validation
public function getActionWords($string, $language = 'english') { $words = $this->getWords($string); $filter = new ActionWordsFilter($language); $actionWords = []; foreach ($words as $word) { $word = $this->removePunctuation($word); if (!is_null($filter->filter($word))) { $actionWords[] = $word; } } return $actionWords; }
php
{ "resource": "" }
q250260
Linguistics.getKeywords
validation
public function getKeywords($string, $amount = 10) { $words = $this->getWords($string); $analysis = new FrequencyAnalysis($words); $keywords = $analysis->getKeyValuesByFrequency(); return array_slice($keywords, 0, $amount); }
php
{ "resource": "" }
q250261
Linguistics.getUniqueWords
validation
public function getUniqueWords($string) { $words = $this->getWords($string); $analysis = new FrequencyAnalysis($words); $words = $analysis->getKeyValuesByFrequency(); return array_unique(array_keys($words)); }
php
{ "resource": "" }
q250262
Linguistics.getWordsByComplexity
validation
public function getWordsByComplexity($string) { $words = $this->getWords($string); $analysis = new FrequencyAnalysis($words); $sortedWords = $analysis->getKeyValuesByFrequency(); $wordsByFrequency = array_unique(array_keys($sortedWords)); usort($wordsByFrequency, function ($a, $b) { return strlen($b) - strlen($a); }); return $wordsByFrequency; }
php
{ "resource": "" }
q250263
Linguistics.getStopWords
validation
public function getStopWords($string, $language = 'english') { $words = $this->getWords($string); $filter = new StopWordsFilter($language); $stopWords = []; foreach ($words as $word) { if (!is_null($filter->filter($word))) { $stopWords[] = $word; } } return $stopWords; }
php
{ "resource": "" }
q250264
Linguistics.hasConfirmation
validation
public function hasConfirmation($string) { $result = false; $words = $this->getWords($string); foreach ($words as $word) { if (in_array($word, $this->confirmationWords)) { $result = true; } } return $result; }
php
{ "resource": "" }
q250265
Linguistics.hasDenial
validation
public function hasDenial($string) { $result = false; $words = $this->getWords($string); foreach ($words as $word) { if (in_array($word, $this->denialWords)) { $result = true; } } return $result; }
php
{ "resource": "" }
q250266
Linguistics.hasUrl
validation
public function hasUrl($string) { $result = false; $words = $this->getWords($string); foreach ($words as $word) { if (preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i", $word)) { $result = true; } } return $result; }
php
{ "resource": "" }
q250267
Linguistics.hasEmail
validation
public function hasEmail($string) { $result = false; $tokenizer = new General(); $words = $tokenizer->tokenize($string); foreach ($words as $word) { if (filter_var($word, FILTER_VALIDATE_EMAIL)) { $result = true; } } return $result; }
php
{ "resource": "" }
q250268
Linguistics.isQuestion
validation
public function isQuestion($string) { $probability = 0; if (strpos($string, '?')) { $probability += 1; } $words = $this->getWords($string); foreach ($this->inquiryWords as $queryWord) { if (!strncmp(strtolower($string), $queryWord, strlen($queryWord))) { $probability += 1; } elseif (stristr(strtolower($string), $queryWord)) { $probability += 0.5; } } if ($probability >= 2) { return true; } return false; }
php
{ "resource": "" }
q250269
AbstractDataFixture.randomizeSamples
validation
protected function randomizeSamples($referencePrefix, array $samples, $limit = 1) { $sample = array_rand($samples, $limit); if (1 === $limit) { $referenceName = sprintf('%s_%s', $referencePrefix, $samples[$sample]); return $this->getReference($referenceName); } else { $collection = new ArrayCollection(); foreach ($sample as $index) { $referenceName = sprintf('%s_%s', $referencePrefix, $samples[$index]); $collection->add($this->getReference($referenceName)); } return $collection; } }
php
{ "resource": "" }
q250270
ErrorController.error
validation
public function error(Request $request) { $this->response->setCode(404); printf("<h2>%s</h2>", HttpStatus::getStatus(404)); printf("Requested document %s on %s could not be found!", $request->getAction(), $request->getController()); }
php
{ "resource": "" }
q250271
ErrorController.exception
validation
public function exception(Request $request) { $ex = $request->getException(); $this->response->setCode(500); printf("<h2>%s</h2>", HttpStatus::getStatus(500)); while ($ex != null) { printf("<h3>%s</h3><pre>%s</pre>", $ex->getMessage(), $ex->getTraceAsString()); $ex = $ex->getPrevious(); } }
php
{ "resource": "" }
q250272
Manager.execute
validation
public function execute(Closure $callback) { foreach ($this->getServices() as $service) { try { return $callback($this->container->make($service)); } catch (Exception $e) { // Move on } } throw new RuntimeException('Could not execute any service.'); }
php
{ "resource": "" }
q250273
TimestampableSubscriber.loadClassMetadata
validation
public function loadClassMetadata(LoadClassMetadataEventArgs $eventArgs) { $this->classMetadata = $eventArgs->getClassMetadata(); $reflectionClass = $this->classMetadata->getReflectionClass(); if (null === $reflectionClass) { return; } if ($this->hasMethod($reflectionClass, 'updateTimestamps')) { $this->addLifecycleCallbacks(); $this->mapFields(); } }
php
{ "resource": "" }
q250274
TimestampableSubscriber.mapField
validation
protected function mapField($field) { if (!$this->classMetadata->hasField($field)) { $this->classMetadata->mapField([ 'fieldName' => $field, 'type' => 'datetime', 'nullable' => true, ]); } }
php
{ "resource": "" }
q250275
Mutex.init
validation
protected function init($key) { if (!isset($this->files[$key])) { $this->files[$key] = fopen($this->dir . $key . '.lockfile', 'w+'); $this->owns[$key] = false; } }
php
{ "resource": "" }
q250276
TopicMapper.persist
validation
public function persist(TopicInterface $thread) { if ($thread->getId() > 0) { $this->update($thread, null, null, new TopicHydrator()); } else { $this->insert($thread, null, new TopicHydrator()); } return $thread; }
php
{ "resource": "" }
q250277
TopicMapper.insert
validation
protected function insert($entity, $tableName = null, HydratorInterface $hydrator = null) { $result = parent::insert($entity, $tableName, $hydrator); $entity->setId($result->getGeneratedValue()); return $result; }
php
{ "resource": "" }
q250278
TopicMapper.update
validation
protected function update($entity, $where = null, $tableName = null, HydratorInterface $hydrator = null) { if (! $where) { $where = 'id = ' . $entity->getId(); } return parent::update($entity, $where, $tableName, $hydrator); }
php
{ "resource": "" }
q250279
Mapper.execute
validation
protected function execute(QueryBuilder $builder): ?Result { return $this->connection->queryArgs($builder->getQuerySql(), $builder->getQueryParameters()); }
php
{ "resource": "" }
q250280
Mapper.getByHash
validation
public function getByHash($columns, string $hash): ?IEntity { if ($this->manager->hasher === null) { throw new MissingServiceException('Hasher is missing'); } return $this->toEntity($this->manager->hasher->hashSQL($this->builder(), $columns, $hash)); }
php
{ "resource": "" }
q250281
Mapper.getMax
validation
public function getMax(string $column): int { return $this->connection->query('SELECT IFNULL(MAX(%column), 0) position FROM %table', $column, $this->getTableName())->fetch()->position; }
php
{ "resource": "" }
q250282
EnvUpdateCommand.getEnvValue
validation
public function getEnvValue(array $expectedEnv, array $actualEnv) { $actualValue = ''; $isStarted = false; foreach ($expectedEnv as $key => $defaultValue) { if (array_key_exists($key, $actualEnv)) { if ($this->option('force')) { $defaultValue = $actualEnv[$key]; } else { $actualValue .= sprintf("%s=%s\n", $key, $actualEnv[$key]); continue; } } if (!$isStarted) { $isStarted = true; if ($this->option('force')) { $this->comment('Update all parameters. Please provide them.'); } else { $this->comment('Some parameters are missing. Please provide them.'); } } $value = $this->ask($key, $defaultValue); // set the prompt value to env $actualValue .= sprintf("%s=%s\n", $key, $value); } return $actualValue; }
php
{ "resource": "" }
q250283
EnvUpdateCommand.emptyEnvironment
validation
private function emptyEnvironment() { foreach (array_keys($_ENV) as $key) { putenv($key); unset($_ENV[$key]); unset($_SERVER[$key]); } }
php
{ "resource": "" }
q250284
SimpleLogger.logImpl
validation
protected function logImpl($level, $message, array $context = array()) { if (! $this->levelHasReached($level)) { return; } if ($this->isRotationNeeded()) { unlink($this->file); } $ms = $this->getMessage($level, $message, $context); $fos = new FileOutputStream($this->file, true); $fos->write($ms); $fos->flush(); $fos->close(); }
php
{ "resource": "" }
q250285
SimpleLogger.isRotationNeeded
validation
private function isRotationNeeded() { clearstatcache(); if (! file_exists($this->file)) { return false; } $result = false; $attributes = stat($this->file); if ($attributes == false || $attributes['size'] >= $this->maxLogSize * 1024 * 1024) { $result = true; } return $result; }
php
{ "resource": "" }
q250286
Settings.getConfig
validation
protected function getConfig() { if ($this->config === null) { if (file_exists($this->filename)) { $this->filename = realpath($this->filename); $this->config = new Config(include $this->filename, true); } else { $this->filename = getcwd() . $this->filename; $this->config = new Config([], true); } } return $this->config; }
php
{ "resource": "" }
q250287
Config.registerType
validation
public function registerType($type, $classname, $options = array()) { if (!class_exists($classname) || !is_callable(array($classname, 'getDataType'))) { return; } $data_type = call_user_func(array($classname, 'getDataType')); $options = (array) $options; $options['type'] = $type; $options['class_name'] = $classname; $options['data_type'] = $data_type; $this->types[$data_type][$type] = $options; }
php
{ "resource": "" }
q250288
Config.getType
validation
public function getType($data_type = 'metadata', $type = 'text') { if (isset($this->types[$data_type][$type])) { return $this->types[$data_type][$type]; } return false; }
php
{ "resource": "" }
q250289
Form.renderFields
validation
private function renderFields($rendered, $fields) { foreach ($fields as $field) { if (! isset($field['name'])) { throw new ControlException("Field must have at least a name!"); } $fieldType = isset($field['type']) ? $field['type'] : 'text'; $id = isset($field['id']) ? $field['id'] : $field['name']; $class = isset($field['class']) ? $field['class'] : $field['name']; $rendered .= sprintf('<input type="%s" id="%s" class="%s" name="%s"/>', $fieldType, $id, $class, $field['name']); } return $rendered; }
php
{ "resource": "" }
q250290
Form.renderButtons
validation
private function renderButtons($rendered, $buttons) { foreach ($buttons as $button) { if (! isset($button['name'])) { throw new ControlException("Button must have at least a name!"); } $buttonType = isset($button['type']) ? $button['type'] : "submit"; $id = isset($button['id']) ? $button['id'] : $button['name']; $class = isset($button['class']) ? $button['class'] : $button['name']; $label = isset($button['label']) ? $button['label'] : $button['name']; $rendered .= sprintf('<button type="%s" id="%s" class="%s" name="%s">%s</button>', $buttonType, $id, $class, $button['name'], $label); } return $rendered; }
php
{ "resource": "" }
q250291
BasicLogger.checkLevel
validation
private static function checkLevel($level) { if ($level != LogLevel::ALERT && $level != LogLevel::CRITICAL && $level != LogLevel::DEBUG && // $level != LogLevel::EMERGENCY && $level != LogLevel::ERROR && $level != LogLevel::INFO && // $level != LogLevel::NOTICE && $level != LogLevel::WARNING) { throw new \Psr\Log\InvalidArgumentException("Invalid log level provided!"); } }
php
{ "resource": "" }
q250292
BasicLogger.getMessage
validation
protected function getMessage($level, $message, array $context = array()): MemoryStream { /** * This check implements the specification request. */ self::checkLevel($level); $ms = new MemoryStream(); $ms->write(strftime("%Y-%m-%d %H:%M:%S", time())); $ms->interpolate("\t[{level}]: ", array( 'level' => sprintf("%6.6s", $level) )); $ms->interpolate($message, $context); $ms->write("\n"); return $ms; }
php
{ "resource": "" }
q250293
MenuExtension.getMenuItemsJson
validation
public function getMenuItemsJson(Collection $menuItems, $currentOwner) { $this->alreadySetIds = []; $this->position = 0; $this->currentOwner = $currentOwner; return json_encode($this->recursiveMenuItemHandling($menuItems)); }
php
{ "resource": "" }
q250294
MenuExtension.recursiveMenuItemHandling
validation
private function recursiveMenuItemHandling(Collection $menuItems) { $data = []; foreach($menuItems as $menuItem) { // This is necessary to avoid to loop on children only when already included as previous parent children if(!in_array($menuItem->getId(), $this->alreadySetIds)) { $this->alreadySetIds[] = $menuItem->getId(); $itemNode = []; $itemNode['name'] = $menuItem->getTitle(); $itemNode['url'] = $menuItem->getTarget(); $itemNode['id'] = $this->position; $itemNode['persist_id'] = $menuItem->getId(); if(null === $menuItem->getParent()) { $itemNode['owner_type'] = get_class($this->currentOwner); $itemNode['owner_id'] = $this->currentOwner->getId(); } $this->position++; if ($menuItem->getChildren()->count() > 0) { $itemNode['children'] = $this->recursiveMenuItemHandling($menuItem->getChildren()); } $data[] = $itemNode; } } return $data; }
php
{ "resource": "" }
q250295
Table.createRelationTable
validation
public function createRelationTable($tableName): self { $table = $this->getTableData($tableName); $name = $this->name . '_x_' . $table->name; return $this->relationTables[] = $this->tableFactory->create($name, $this->prefix); }
php
{ "resource": "" }
q250296
Table.addColumnToRename
validation
public function addColumnToRename(string $name, Column $column): self { $this->oldColumns[$name] = $column; return $this; }
php
{ "resource": "" }
q250297
Table.changeColumns
validation
private function changeColumns(): void { $change = []; foreach ($this->oldColumns as $name => $column) { if ($this->columnExists($name)) { $change[] = "[$name] $column"; } } if (!empty($change)) { $this->connection->query("ALTER TABLE %table CHANGE " . implode(', CHANGE ', $change), $this->name); } }
php
{ "resource": "" }
q250298
Table.addPrimaryKey
validation
public function addPrimaryKey(string $name): Column { $column = $this->addColumn($name); $this->setPrimaryKey($name); return $column; }
php
{ "resource": "" }
q250299
Table.addForeignKey
validation
public function addForeignKey(string $name, $mapperClass, $onDelete = true, $onUpdate = false): Column { $table = $this->getTableData($mapperClass); $constrait = new Constrait($name, $this, $table, $onDelete, $onUpdate); $this->constraints[$constrait->name] = $constrait; return $constrait->column; }
php
{ "resource": "" }