Esempio n. 1
0
 function user_function_sort($arr)
 {
     usort($arr, function ($a, $b) {
         return strnatcmp($a['value'], $b['value']);
     });
     return $arr;
 }
Esempio n. 2
0
 public function sort(ProxySourceItem $a, ProxySourceItem $b)
 {
     if ($a->date() && $a->title() && $b->date() && $b->title()) {
         return strnatcmp($b->date() . ' ' . $b->title(), $a->date() . ' ' . $a->title());
     }
     return strnatcmp($a->relativePathname(), $b->relativePathname());
 }
Esempio n. 3
0
function _c_sort($a, $b)
{
    global $ary;
    $a_re = false;
    $b_re = false;
    $i = 0;
    foreach ($ary as $nanme => $regexp) {
        if ($a_re !== false && $b_re !== false) {
            break;
        }
        if ($a_re === false && preg_match($regexp, $a)) {
            $a_re = $i;
        }
        if ($b_re === false && preg_match($regexp, $b)) {
            $b_re = $i;
        }
        $i++;
    }
    if ($a_re < $b_re) {
        return -1;
    } elseif ($a_re > $b_re) {
        return 1;
    } else {
        return strnatcmp($a, $b);
    }
}
Esempio n. 4
0
 public function sortOpponents($key, $order)
 {
     // sort teams by column name in $key, order is either 'asc' or 'desc'
     return function ($a, $b) use($key, $order) {
         return $order === 'desc' ? strnatcmp($b->{$key}, $a->{$key}) : strnatcmp($a->{$key}, $b->{$key});
     };
 }
Esempio n. 5
0
 public function get()
 {
     /** @var \Tacit\Model\Persistent $modelClass */
     $modelClass = static::$modelClass;
     $criteria = $this->criteria(func_get_args());
     $limit = $this->app->request->get('limit', 25);
     $offset = $this->app->request->get('offset', 0);
     $orderBy = $this->app->request->get('sort', $modelClass::key());
     $orderDir = $this->app->request->get('sort_dir', 'desc');
     try {
         $total = $modelClass::count($criteria, $this->app->container->get('repository'));
         $collection = $modelClass::find($criteria, [], $this->app->container->get('repository'));
         if ($collection === null) {
             $collection = [];
         }
         if ($collection && $orderBy) {
             usort($collection, function ($a, $b) use($orderBy, $orderDir) {
                 switch ($orderDir) {
                     case 'desc':
                     case 'DESC':
                     case -1:
                         return strnatcmp($b->{$orderBy}, $a->{$orderBy});
                     default:
                         return strnatcmp($a->{$orderBy}, $b->{$orderBy});
                 }
             });
         }
         if ($collection && $limit > 0) {
             $collection = array_slice($collection, $offset, $limit);
         }
     } catch (\Exception $e) {
         throw new ServerErrorException($this, 'Error retrieving collection', $e->getMessage(), null, $e);
     }
     $this->respondWithCollection($collection, $this->transformer(), ['total' => $total]);
 }
Esempio n. 6
0
 public function index($tab = '', $page = '')
 {
     $modules = $objects = array();
     foreach ($this->addons->get_modules(TRUE) as $module) {
         foreach ($module->get_access() as $type => $access) {
             if (!empty($access['get_all']) && ($get_all = call_user_func($access['get_all']))) {
                 $modules[$module->name] = array($module, $module->icon, $type, $access);
                 $objects[$module->name] = $get_all;
             }
         }
     }
     uasort($modules, function ($a, $b) {
         return strnatcmp($a[0]->get_title(), $b[0]->get_title());
     });
     foreach ($modules as $module_name => $module) {
         if ($tab === '' || $module_name == $tab) {
             $objects = $objects[$module_name];
             foreach ($objects as &$object) {
                 list($id, $title) = array_values($object);
                 $object = array('id' => $id, 'title' => $module[0]->load->lang($title, NULL));
                 unset($object);
             }
             $tab = $module_name;
             break;
         }
     }
     return array($this->load->library('pagination')->get_data($objects, $page), $modules, $tab);
 }
Esempio n. 7
0
/**
 * PHP version check
 *
 * @param $ver minimum version number
 * @return true if we are running at least PHP $ver
 */
function php_min_ver($ver)
{
    if (strnatcmp(phpversion(), $ver) < 0) {
        return false;
    }
    return true;
}
function subscriptions_compare_by_name($a, $b)
{
    $an = $a['name'];
    $bn = $b['name'];
    $result = strnatcmp($an, $bn);
    return $result;
}
 public function actionProcess($num, FactorizationService $factorizationService, Connection $redis, Response $response)
 {
     $factors = $errorMsg = '';
     if (PHP_INT_SIZE === 4) {
         $maxInt = "2147483647";
     } else {
         $maxInt = "9223372036854775807";
     }
     try {
         if (preg_match('#\\D#', $num)) {
             throw new Exception('В числе должны быть только цифры.');
         }
         if (0 < strnatcmp((string) $num, (string) $maxInt)) {
             throw new Exception('Слишком большое число.');
         }
         if ($factors = $redis->hget(self::HASH_KEY, $num)) {
             $factors = unserialize($factors);
         } else {
             $factors = $factorizationService->trialDivision((int) $num);
             if ($redis->hlen(self::HASH_KEY) == self::MAX_HASH_LEN) {
                 $redis->del(self::HASH_KEY);
             }
             $redis->hset(self::HASH_KEY, $num, serialize($factors));
         }
     } catch (Exception $e) {
         $errorMsg = $e->getMessage();
     }
     $response->format = Response::FORMAT_JSON;
     return ['data' => $factors, 'error' => $errorMsg];
 }
Esempio n. 10
0
 /**
  * Performs a comparison between two values and returns an integer result, like strnatcmp.
  *
  * @param string $value1
  * @param string $value2
  * @return int
  */
 public static function compare($value1, $value2)
 {
     if (self::isIntlLoaded()) {
         return self::getCollator()->compare($value1, $value2);
     }
     return strnatcmp($value1, $value2);
 }
Esempio n. 11
0
 /**
  * Scan the directory at the given path and include
  * all files. Only 1 level iteration.
  *
  * @param string $path The directory/file path.
  * @return bool True. False if not appended.
  */
 protected function append($path)
 {
     $files = [];
     if (is_dir($path)) {
         $dir = new \DirectoryIterator($path);
         foreach ($dir as $file) {
             if (!$file->isDot() || !$file->isDir()) {
                 $file_extension = pathinfo($file->getFilename(), PATHINFO_EXTENSION);
                 if ($file_extension === 'php') {
                     $this->names[] = $file->getBasename('.php');
                     $files[] = ['name' => $file->getBasename('.php'), 'path' => $file->getPath() . DS . $file->getBasename()];
                 }
             }
         }
         // Organize files per alphabetical order
         // and include them.
         if (!empty($files)) {
             usort($files, function ($a, $b) {
                 return strnatcmp($a['name'], $b['name']);
             });
             foreach ($files as $file) {
                 include_once $file['path'];
             }
         }
         return true;
     }
     return false;
 }
 function index()
 {
     /**
      * If the PHP version is greater than 5.3.0 it
      * will support Anonymous functions
      */
     if (strnatcmp(phpversion(), '5.3.0') >= 0) {
         add_action('before_title', function () {
             echo '<small>This text is prepended before the title</small>';
         });
         add_action('after_title', function () {
             echo '<small>This text is appended after the title</small> <hr/>';
         });
     }
     /**
      * Add some class specific actions
      */
     add_action('before_content', array($this, 'action_before_content'));
     add_action('after_content', array($this, 'action_after_content'));
     /**
      * Add filters to the content (1 global function and 1 class specific function)
      */
     add_filter('content', 'replace_ipsum', 30);
     //global function (see above) with 30 priority
     add_filter('content', array($this, 'filter_add_author_to_content'), 10);
     //class function (see below) with 10 priority (first executed)
     /**
      *  add time to the title and underline the word title
      */
     add_filter('title', array($this, 'filter_add_time_to_the_title'));
     //add a time to the title
     $data = array('content' => 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi at sem leo. Pellentesque sed ipsum tortor sed mi gravida imperdiet ac sed magna. Nunc tempor libero nec ligula ullamcorper euismod. Sed adipiscing consectetur metus eget congue. ipsum dignissim mauris nec risus tempus vulputate. Ut in arcu felis. Sed imperdiet mollis ipsum. Aliquam non lacus libero, eu tristique urna. ipsum Morbi vel gravida justo. Curabitur sed velit lorem, nec ultrices odio. Cras et magna vel purus dapibus egestas. Etiam massa eros, pretium eget venenatis fermentum, tincidunt id nisl. Aenean ut felis velit. Donec non neque congue nibh convallis pretium. Nam egestas luctus eros ac elementum. Vestibulum nisl sapien, pellentesque sit amet pulvinar at, ullamcorper in purus.');
     $this->load->view('hooking_example', $data);
 }
Esempio n. 13
0
 public static function sort(&$paths, $method, $direction)
 {
     if (!self::validOrderMethod($method) || !self::validOrderDirection($direction)) {
         throw new Exception('Invalid order params');
     }
     if ($method === 'name') {
         usort($paths, function ($a, $b) {
             return strnatcmp($a->name, $b->name);
         });
     } elseif ($method === 'time') {
         usort($paths, function ($a, $b) {
             if ($a->rawTime === $b->rawTime) {
                 return 0;
             }
             return $a->rawTime > $b->rawTime ? 1 : -1;
         });
     }
     if ($method === 'size') {
         usort($paths, function ($a, $b) {
             if ($a->rawSize === $b->rawSize) {
                 return 0;
             }
             return $a->rawSize > $b->rawSize ? 1 : -1;
         });
     }
     if ($direction === 'desc') {
         $paths = array_reverse($paths);
     }
 }
 /**
  * Converts the raw configuration file content to an configuration object storage
  *
  * @param string $extensionKey Extension key
  * @return array
  */
 protected function getConfigurationArrayFromExtensionKey($extensionKey)
 {
     /** @var $configurationUtility \TYPO3\CMS\Extensionmanager\Utility\ConfigurationUtility */
     $configurationUtility = $this->objectManager->get(\TYPO3\CMS\Extensionmanager\Utility\ConfigurationUtility::class);
     $defaultConfiguration = $configurationUtility->getDefaultConfigurationFromExtConfTemplateAsValuedArray($extensionKey);
     $resultArray = array();
     if (!empty($defaultConfiguration)) {
         $metaInformation = $this->addMetaInformation($defaultConfiguration);
         $configuration = $this->mergeWithExistingConfiguration($defaultConfiguration, $extensionKey);
         $hierarchicConfiguration = array();
         foreach ($configuration as $configurationOption) {
             $originalConfiguration = $this->buildConfigurationArray($configurationOption, $extensionKey);
             ArrayUtility::mergeRecursiveWithOverrule($originalConfiguration, $hierarchicConfiguration);
             $hierarchicConfiguration = $originalConfiguration;
         }
         // Flip category array as it was merged the other way around
         $hierarchicConfiguration = array_reverse($hierarchicConfiguration);
         // Sort configurations of each subcategory
         foreach ($hierarchicConfiguration as &$catConfigurationArray) {
             foreach ($catConfigurationArray as &$subcatConfigurationArray) {
                 uasort($subcatConfigurationArray, function ($a, $b) {
                     return strnatcmp($a['subcat'], $b['subcat']);
                 });
             }
             unset($subcatConfigurationArray);
         }
         unset($tempConfiguration);
         ArrayUtility::mergeRecursiveWithOverrule($hierarchicConfiguration, $metaInformation);
         $resultArray = $hierarchicConfiguration;
     }
     return $resultArray;
 }
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $output->writeln('Sync our local folder with the S3 Bucket...');
     $sync = $this->getApplication()->make('operations.s3-sync');
     $sync->sync();
     $output->writeln('Getting the list of files to be processed...');
     $finder = new Finder();
     $finder->files('*.json')->in($this->directories['files_dir'])->sort(function ($a, $b) {
         return strnatcmp($a->getRealPath(), $b->getRealPath());
     });
     if (file_exists($this->directories['last_read_file'])) {
         $lastFile = file_get_contents($this->directories['last_read_file']);
         $finder->filter(function ($file) use($lastFile) {
             if (0 >= strnatcmp($file->getFilename(), $lastFile)) {
                 return false;
             }
             return true;
         });
     }
     $importer = $this->getApplication()->make('operations.file-importer');
     foreach ($finder as $file) {
         $output->writeln('Processing the events from ' . $file->getFilename() . '...');
         $importer->from($file);
         file_put_contents($this->directories['last_read_file'], $file->getFilename());
     }
 }
Esempio n. 16
0
function build_sorter($key)
{
    //build sorter creates function to sort array by specified key
    return function ($a, $b) use($key) {
        return strnatcmp($a[$key], $b[$key]);
    };
}
Esempio n. 17
0
 public function registerModule($baseDir, $MODULE_NAME)
 {
     // read module.ini file (if it exists) from module's directory
     if (file_exists("{$baseDir}/{$MODULE_NAME}/module.ini")) {
         $entries = parse_ini_file("{$baseDir}/{$MODULE_NAME}/module.ini");
         // check that current PHP version is greater or equal than module's
         // minimum required PHP version
         if (isset($entries["minimum_php_version"])) {
             $minimum = $entries["minimum_php_version"];
             $current = phpversion();
             if (strnatcmp($minimum, $current) > 0) {
                 $this->logger->log('WARN', "Could not load module" . " {$MODULE_NAME} as it requires at least PHP version '{$minimum}'," . " but current PHP version is '{$current}'");
                 return;
             }
         }
     }
     $newInstances = $this->getNewInstancesInDir("{$baseDir}/{$MODULE_NAME}");
     foreach ($newInstances as $name => $className) {
         $obj = new $className();
         $obj->moduleName = $MODULE_NAME;
         if (Registry::instanceExists($name)) {
             $this->logger->log('WARN', "Instance with name '{$name}' already registered--replaced with new instance");
         }
         Registry::setInstance($name, $obj);
     }
     if (count($newInstances) == 0) {
         $this->logger->log('ERROR', "Could not load module {$MODULE_NAME}. No classes found with @Instance annotation!");
         return;
     }
 }
Esempio n. 18
0
 /**
  * Add a table with the specified columns to the lookup.
  *
  * The data should be an associative array with the following data:
  * 'display_name' => The translation key to display in the select list
  * 'columns'      => An array containing the table's columns
  *
  * @param string $context Context for data
  * @param array  $data    Data array for the table
  *
  * @return ReportBuilderEvent
  */
 public function addTable($context, array $data, $group = null)
 {
     $data['group'] = null == $group ? $context : $group;
     foreach ($data['columns'] as $column => &$d) {
         $d['label'] = $this->translator->trans($d['label']);
         if (!isset($d['alias'])) {
             $d['alias'] = substr($column, ($pos = strpos($column, '.')) !== false ? $pos + 1 : 0);
         }
     }
     uasort($data['columns'], function ($a, $b) {
         return strnatcmp($a['label'], $b['label']);
     });
     if (isset($data['filters'])) {
         foreach ($data['filters'] as $column => &$d) {
             $d['label'] = $this->translator->trans($d['label']);
             if (!isset($d['alias'])) {
                 $d['alias'] = substr($column, ($pos = strpos($column, '.')) !== false ? $pos + 1 : 0);
             }
         }
         uasort($data['filters'], function ($a, $b) {
             return strnatcmp($a['label'], $b['label']);
         });
     }
     $this->tableArray[$context] = $data;
     if ($this->context == $context) {
         $this->stopPropagation();
     }
     return $this;
 }
Esempio n. 19
0
 /**
  * Get Resource JSON_LD content
  * 
  * @param type $uri
  * @return string
  */
 public function getResource($uri = "", $pretty = false)
 {
     // Check if the GRAPH URI is set
     if (empty($this->options['graph_uri'])) {
         return "";
     }
     $resource = "";
     if (strcmp($uri, "") !== 0) {
         $resource = $uri;
     } elseif (strcmp($this->resource, "") !== 0) {
         $resource = $this->resource;
     } else {
         return "";
     }
     $api = $this->readLink($resource);
     $schemadata = "";
     $ctx = stream_context_create(array('http' => array('method' => "GET", 'timeout' => 5)));
     // Process API, get results
     if (false !== ($schemadata = @file_get_contents($api, false, $ctx))) {
         // Check for empty result, HTTP Response Code 204 is legit, no custom data
         if (empty($schemadata) || $schemadata === "null") {
             $schemadata = "";
         } elseif ($pretty && strnatcmp(phpversion(), '5.4.0') >= 0) {
             $schemaObj = json_decode($schemadata);
             $schemadata = json_encode($schemaObj, JSON_PRETTY_PRINT);
         }
     } else {
         // error happened
         $schemadata = "";
     }
     return $schemadata;
 }
Esempio n. 20
0
 public function sort(ProxySourceItem $a, ProxySourceItem $b)
 {
     if ($this->reversed) {
         return strnatcmp($b[$this->key], $a[$this->key]);
     }
     return strnatcmp($a[$this->key], $b[$this->key]);
 }
Esempio n. 21
0
 /**
  * Check if installed CodeIgniter version is the latest
  *
  * @access	public
  * @return	bool
  */
 public function check_codeigniter()
 {
     $latest_version = file_get_contents('http://versions.ellislab.com/codeigniter_version.txt');
     if (strnatcmp(str_replace('-dev', '', CI_VERSION), $latest_version) >= 0) {
         return TRUE;
     }
     return FALSE;
 }
Esempio n. 22
0
 public function activity($config = array())
 {
     $users = $this->db->select('DISTINCT u.user_id', 'u.username')->from('nf_sessions s')->join('nf_users u', 'u.user_id = s.user_id', 'INNER')->where('s.last_activity > DATE_SUB(NOW(), INTERVAL 5 MINUTE)')->where('s.is_crawler', FALSE)->get();
     usort($users, function ($a, $b) {
         return strnatcmp(strtolower($a['username']), strtolower($b['username']));
     });
     return new Panel(array('title' => $this('forum_activity'), 'icon' => 'fa-globe', 'content' => $this->load->view('activity', array('users' => $users, 'visitors' => $this->db->select('COUNT(*)')->from('nf_sessions')->where('user_id', NULL)->where('last_activity > DATE_SUB(NOW(), INTERVAL 5 MINUTE)')->where('is_crawler', FALSE)->row()))));
 }
Esempio n. 23
0
function cmp($a, $b)
{
    $ret = strnatcmp($a['lastname'], $b['lastname']);
    if (!$ret) {
        $ret = strnatcmp($a['firstname'], $b['firstname']);
    }
    return $ret;
}
Esempio n. 24
0
 /**
  * Gets a sorted list of all listeners
  * @return array
  */
 public function getListeners()
 {
     // sort by priority
     uksort($this->listeners, function ($a, $b) {
         return strnatcmp($a, $b);
     });
     return $this->listeners;
 }
Esempio n. 25
0
function phpbb_rnatsort($array)
{
    $strrnatcmp = function ($a, $b) {
        return strnatcmp($b, $a);
    };
    usort($array, $strrnatcmp);
    return $array;
}
Esempio n. 26
0
 protected function getUserDataSortedByLastName()
 {
     $data = $this->getUserDataUnsorted();
     usort($data, function ($user1, $user2) {
         return strnatcmp($user1["lastName"], $user2["lastName"]);
     });
     return $data;
 }
Esempio n. 27
0
function orderDateName($a, $b)
{
    $retval = strnatcmp($b['path'], $a['path']);
    if (!$retval) {
        return strnatcmp($a['file'], $b['file']);
    }
    return $retval;
}
 function data_sort($a, $b)
 {
     $orderby = !empty($_REQUEST['orderby']) ? $_REQUEST['orderby'] : key($a);
     $order = !empty($_REQUEST['order']) ? strtolower($_REQUEST['order']) : 'asc';
     $a[$orderby] = preg_replace("/(?![.=\$'€%-])\\p{P}/u", '', $a[$orderby]);
     $b[$orderby] = preg_replace("/(?![.=\$'€%-])\\p{P}/u", '', $b[$orderby]);
     $result = strnatcmp($a[$orderby], $b[$orderby]);
     return $order === 'asc' ? $result : -$result;
 }
Esempio n. 29
0
 /**
  * Sorting names array for translator name selector
  * @param array $arr
  * @return array
  */
 function sort_names($arr)
 {
     usort($arr, function ($a, $b) {
         $first = $a['menu_name'];
         $second = $b['menu_name'];
         return strnatcmp($first, $second);
     });
     return $arr;
 }
Esempio n. 30
0
 public function init()
 {
     // We have special sorting rules for our items based on the date
     // and title. This assumes that the items are actually Project instances.
     uasort($this->items, function ($a, $b) {
         return strnatcmp($b->date() . ' ' . $b->title(), $a->date() . ' ' . $a->title());
     });
     parent::init();
 }