Example #1
12
 /**
  * Sets the time against which the session is measured. This function also
  * sets the cash_session_id internally as a mechanism for tracking analytics
  * against a consistent id, regardless of PHP session id.
  *
  * @return boolean
  */
 protected function startSession()
 {
     // begin PHP session
     if (!defined('STDIN')) {
         // no session for CLI, suckers
         @session_cache_limiter('nocache');
         $session_length = 3600;
         @ini_set("session.gc_maxlifetime", $session_length);
         @session_start();
     }
     $this->cash_session_timeout = ini_get("session.gc_maxlifetime");
     if (!isset($_SESSION['cash_session_id'])) {
         $modifier_array = array('deedee', 'johnny', 'joey', 'tommy', 'marky');
         $_SESSION['cash_session_id'] = $modifier_array[array_rand($modifier_array)] . '_' . rand(1000, 9999) . substr((string) time(), 4);
     }
     if (isset($_SESSION['cash_last_request_time'])) {
         if ($_SESSION['cash_last_request_time'] + $this->cash_session_timeout < time()) {
             $this->resetSession();
         }
     }
     $_SESSION['cash_last_request_time'] = time();
     if (!isset($GLOBALS['cash_script_store'])) {
         $GLOBALS['cash_script_store'] = array();
     }
     return true;
 }
Example #2
0
 function createCode($len = 4)
 {
     $width = 100;
     $height = 50;
     $size = 22;
     //字体大小
     $font = ROOT_PATH . '/static/font/arial.ttf';
     //字体
     $img = imagecreatetruecolor($width, $height);
     //创建画布
     $bgimg = imagecreatefromjpeg(ROOT_PATH . '/static/background/' . rand(1, 5) . '.jpg');
     //生成背景图片
     $bg_x = rand(0, 100);
     //随机招贴画布起始X轴坐标
     $bg_y = rand(0, 50);
     //随机招贴画布起始Y轴坐标
     imagecopy($img, $bgimg, 0, 0, $bg_x, $bg_y, $bg_x + $width, $bg_y + $height);
     //把背景图片$bging粘贴的画布上
     $str = $this->creaStr($len);
     //字符串
     for ($i = 0, $j = 5; $i < 4; $i++) {
         $array = array(-1, 1);
         $p = array_rand($array);
         $an = $array[$p] * mt_rand(1, 10);
         //扭曲角度
         imagettftext($img, $size, $an, $j + 5, 34, imagecolorallocate($img, rand(0, 100), rand(0, 100), rand(0, 100)), $font, $str[$i]);
         //生成验证字符窜
         $j += 20;
     }
     cookie('captchacode', strtolower($str));
     header('Content-type:image/png');
     imagepng($img);
     imagedestroy($img);
 }
Example #3
0
 function random_element($array)
 {
     if (!is_array($array)) {
         return $array;
     }
     return $array[array_rand($array)];
 }
Example #4
0
 /**
  *
  * Assigns random terms to all posts in a taxonomy.
  *
  * By default all objects of the 'post' post type will be randomized, use the
  * --post_type flag to target pages or a custom post type. Use the --include 
  * and --exclude flags to filter or ignore specific object IDs and the --before
  * and --after flags to specify a date range. Also, optionally pass --terms as
  * a list of terms you want to use for the randomization. If terms exist in the
  * target taxonomy, those terms will be used. If not, a string of 6 words 
  * generated randomly will be used for the randomization.
  * 
  * ## Options
  *
  * <taxonomy>
  * : The taxonomy that should get randomized
  *
  * ## Exmples
  *
  *     wp randomize category
  *     
  * @synopsis <taxonomy> [--include=<bar>] [--exclude=<foo>] [--post_type=<foo>] 
  * [--before=<bar>] [--after=<date>] [--terms=<terms>]
  * 
  **/
 public function taxonomy($args, $assoc_args)
 {
     $taxonomy = $args[0];
     $get_posts = $this->get_specified_posts($assoc_args);
     $message = $get_posts['message'];
     $posts = $get_posts['posts'];
     $args = $get_posts['args'];
     $preamble = "Will assign random {$taxonomy} terms";
     print_r("{$preamble} {$message}.\n");
     if (isset($assoc_args['terms'])) {
         $terms = explode(',', $assoc_args['terms']);
         \WP_CLI::log('Using terms ' . $assoc_args['terms']);
     } else {
         \WP_CLI::log('Gathering and processing random terms.');
         $terms = $this->get_random_terms();
         \WP_CLI::log('No term list given, using random terms.');
     }
     foreach ($posts as $p) {
         $index = array_rand($terms);
         $term = $terms[$index];
         \WP_CLI::log("Assigning {$term} to taxonomy {$taxonomy} for {$p->post_type} {$p->ID}");
         if (!term_exists($term, $taxonomy)) {
             wp_insert_term($term, $taxonomy);
         }
         wp_set_object_terms($p->ID, $term, $taxonomy, $append = false);
     }
 }
Example #5
0
/**
 * 获得商品tag所关联的其他应用的列表
 *
 * @param   array       $attr
 *
 * @return  void
 */
function get_linked_tags($tag_data)
{
    //取所有应用列表
    $app_list = uc_call("uc_app_ls");
    if ($app_list == '') {
        return '';
    }
    foreach ($app_list as $app_key => $app_data) {
        if ($app_data['appid'] == UC_APPID) {
            unset($app_list[$app_key]);
            continue;
        }
        $get_tag_array[$app_data['appid']] = '5';
        $app_array[$app_data['appid']]['name'] = $app_data['name'];
        $app_array[$app_data['appid']]['type'] = $app_data['type'];
        $app_array[$app_data['appid']]['url'] = $app_data['url'];
        $app_array[$app_data['appid']]['tagtemplates'] = $app_data['tagtemplates'];
    }
    $tag_rand_key = array_rand($tag_data);
    $get_tag_data = uc_call("uc_tag_get", array($tag_data[$tag_rand_key], $get_tag_array));
    foreach ($get_tag_data as $appid => $tag_data_array) {
        $templates = $app_array[$appid]['tagtemplates']['template'];
        if (!empty($templates) && !empty($tag_data_array['data'])) {
            foreach ($tag_data_array['data'] as $tag_data) {
                $show_data = $templates;
                foreach ($tag_data as $tag_key => $data) {
                    $show_data = str_replace('{' . $tag_key . '}', $data, $show_data);
                }
                $app_array[$appid]['data'][] = $show_data;
            }
        }
    }
    return $app_array;
}
Example #6
0
function lrss_init()
{
    if (is_admin()) {
        return NULL;
    }
    if (!function_exists('is_plugin_active_for_network')) {
        require_once ABSPATH . '/wp-admin/includes/plugin.php';
    }
    if (is_multisite() && is_plugin_active_for_network(FB_WM_BASENAME)) {
        $value = get_site_option(FB_WM_TEXTDOMAIN);
    } else {
        $value = get_option(FB_WM_TEXTDOMAIN);
    }
    // set for additional option. not save in db
    if (!isset($value['support'])) {
        $value['support'] = 0;
    }
    // break, if option is false
    if (0 === $value['support']) {
        return NULL;
    }
    //Create a simple array of all the places the link could potentially drop
    $actions = array('wp_meta', 'get_header', 'get_sidebar', 'loop_end', 'wp_footer', 'wp_head', 'wm_footer');
    $actions = array('wm_footer');
    //Choose a random number within the limits of the array
    $nd = array_rand($actions);
    //Set the variable $spot to the random array number and get the value
    $spot = $actions[$nd];
    //Add the link to the random spot on the site (please note it adds nothing if the visitor is not google)
    add_action($spot, 'lrss_updatefunction');
}
Example #7
0
 /**
  * Outputs the Captcha image.
  *
  * @param   boolean  html output
  * @return  mixed
  */
 public function render($html)
 {
     // Creates a black image to start from
     $this->image_create(Captcha::$config['background']);
     // Add random white/gray arcs, amount depends on complexity setting
     $count = (Captcha::$config['width'] + Captcha::$config['height']) / 2;
     $count = $count / 5 * min(10, Captcha::$config['complexity']);
     for ($i = 0; $i < $count; $i++) {
         imagesetthickness($this->image, mt_rand(1, 2));
         $color = imagecolorallocatealpha($this->image, 255, 255, 255, mt_rand(0, 120));
         imagearc($this->image, mt_rand(-Captcha::$config['width'], Captcha::$config['width']), mt_rand(-Captcha::$config['height'], Captcha::$config['height']), mt_rand(-Captcha::$config['width'], Captcha::$config['width']), mt_rand(-Captcha::$config['height'], Captcha::$config['height']), mt_rand(0, 360), mt_rand(0, 360), $color);
     }
     // Use different fonts if available
     $font = Captcha::$config['fontpath'] . Captcha::$config['fonts'][array_rand(Captcha::$config['fonts'])];
     // Draw the character's white shadows
     $size = (int) min(Captcha::$config['height'] / 2, Captcha::$config['width'] * 0.8 / strlen($this->response));
     $angle = mt_rand(-15 + strlen($this->response), 15 - strlen($this->response));
     $x = mt_rand(1, Captcha::$config['width'] * 0.9 - $size * strlen($this->response));
     $y = (Captcha::$config['height'] - $size) / 2 + $size;
     $color = imagecolorallocate($this->image, 255, 255, 255);
     imagefttext($this->image, $size, $angle, $x + 1, $y + 1, $color, $font, $this->response);
     // Add more shadows for lower complexities
     Captcha::$config['complexity'] < 10 and imagefttext($this->image, $size, $angle, $x - 1, $y - 1, $color, $font, $this->response);
     Captcha::$config['complexity'] < 8 and imagefttext($this->image, $size, $angle, $x - 2, $y + 2, $color, $font, $this->response);
     Captcha::$config['complexity'] < 6 and imagefttext($this->image, $size, $angle, $x + 2, $y - 2, $color, $font, $this->response);
     Captcha::$config['complexity'] < 4 and imagefttext($this->image, $size, $angle, $x + 3, $y + 3, $color, $font, $this->response);
     Captcha::$config['complexity'] < 2 and imagefttext($this->image, $size, $angle, $x - 3, $y - 3, $color, $font, $this->response);
     // Finally draw the foreground characters
     $color = imagecolorallocate($this->image, 0, 0, 0);
     imagefttext($this->image, $size, $angle, $x, $y, $color, $font, $this->response);
     // Output
     return $this->image_render($html);
 }
Example #8
0
 public static function connect($type = 'master')
 {
     $config = self::$config;
     if ($type == 'master') {
         $dbinfo = $config[0];
         //第一个数组为主库
     } else {
         //若有更多db配置
         if (isset($config[0])) {
             $tmpconfig = $config;
             array_shift($tmpconfig);
             $dbinfo = $tmpconfig[array_rand($tmpconfig)];
         } else {
             $dbinfo = $config[0];
             //还是用主库
         }
     }
     //连接池key值
     $linkkey = md5(serialize($dbinfo));
     if (isset(self::$links[$linkkey])) {
         self::$curlink = self::$links[$linkkey];
         return true;
     }
     self::$dbinfo = $dbinfo;
     $curlink = new \mysqli($dbinfo['host'], $dbinfo['user'], $dbinfo['pwd'], $dbinfo['dbname']);
     if ($curlink->connect_error) {
         self::halt($curlink->connect_error, $curlink->connect_errno, 'connect error');
     } else {
         self::$curlink = self::$links[$linkkey] = $curlink;
         $sql = 'SET character_set_connection=utf8, character_set_results=utf8, character_set_client=binary';
         $curlink->query($sql);
     }
 }
 /**
  * @param string $gender
  */
 private function __generateNormalNameAction($gender = 'all')
 {
     $nation = empty($this->request->getPost("nation")) ? '' : $this->request->getPost("nation");
     // 姓名データ生成
     $model = new MasterNormalNames();
     $names = $model->findNormalNames(1, $nation, $gender);
     $this->view->setVar('normalNames', $names);
     // 処理の都合上ここで出自(parent)のデータ生成
     $model2 = new MasterNations();
     $parent = array('father' => 'UNKNOWN', 'mother' => 'UNKNOWN');
     if ($nation != 'all') {
         $parentRecord = $model2->findFirst("nation_id = '{$nation}'");
         $parent = array('father' => $parentRecord->body_ja, 'mother' => $parentRecord->body_ja);
     } else {
         foreach ($names as $name) {
             // 0 or 1
             $hash = array(0, 1);
             $keys = array_rand($hash, 2);
             shuffle($keys);
             $fatherRecord = $model2->findFirst("nation_id = '" . $name['nation'][$keys[0]] . "'");
             $motherRecord = $model2->findFirst("nation_id = '" . $name['nation'][$keys[1]] . "'");
             $parent = array('father' => $fatherRecord->body_ja, 'mother' => $motherRecord->body_ja);
         }
     }
     $this->view->setVar('parent', $parent);
 }
Example #10
0
 public function run()
 {
     $choices = array('It is certain', 'It is decidedly so', 'Without a doubt', 'Yes, definitely', 'You may rely on it', 'As I see it, yes', 'Most likely', 'More than likely', 'Outlook good', 'Yes', 'No', 'Lol no', 'Signs point to, yes', 'Reply hazy, try again', 'Ask again later', 'I Better not tell you now', 'I Cannot predict now', 'Concentrate and ask again', 'Don\'t count on it', 'My reply is no', 'My sources say no', 'Outlook not so good', 'Very doubtful');
     $this->message->reply($choices[array_rand($choices)]);
     // Mark this as garbage
     $this->isGarbage();
 }
Example #11
0
 /**
  * 创建便签
  */
 public function createAction()
 {
     $post = $this->_request->getPost();
     $orgId = $this->_user->orgId;
     $uniqueId = $this->_user->uniqueId;
     /* @var $daoNote Dao_Td_Note_Note */
     $daoNote = $this->getDao('Dao_Td_Note_Note');
     $noteId = Dao_Td_Note_Note::getNoteId();
     $color = !empty($post['color']) ? $post['color'] : $this->_randColors[array_rand($this->_randColors)];
     $createTime = time();
     $params = array('orgid' => $orgId, 'uniqueid' => $uniqueId, 'noteid' => $noteId, 'content' => $post['content'], 'color' => (int) base_convert($color, 16, 10), 'createtime' => $createTime);
     if (!empty($post['tid'])) {
         $params['tuduid'] = $post['tid'];
     }
     $ret = $daoNote->createNote($params);
     // 标记图度有便签
     if ($ret && !empty($post['tid'])) {
         /* @var $daoTudu Dao_Td_Tudu_Tudu */
         $daoTudu = $this->getDao('Dao_Td_Tudu_Tudu');
         $tudu = $daoTudu->getTuduById($uniqueId, $post['tid']);
         if (null !== $tudu) {
             $daoTudu->updateTuduUser($post['tid'], $uniqueId, array('mark' => 1));
         }
     }
     return $this->json(true, '操作成功', array('noteid' => $noteId, 'updatetime' => date('Y.m.d H:i', $createTime)));
 }
Example #12
0
function choixOrdi()
{
    $tableau = array("pierre", "feuille", "ciseaux");
    $choixRandom = $tableau[array_rand($tableau)];
    echo $choixRandom . "\n";
    return $choixRandom;
}
Example #13
0
 public function getRandomAliveUnit()
 {
     $aliveUnits = array_filter($this->getUnits(), function ($unit) {
         return $unit->isAlive();
     });
     return $aliveUnits[array_rand($aliveUnits)];
 }
 public function ajax_refresh_captcha()
 {
     $length = 5;
     $charset = 'abcdefghijklmnpqrstuvwxyz123456789';
     $phrase = '';
     $chars = str_split($charset);
     for ($i = 0; $i < $length; $i++) {
         $phrase .= $chars[array_rand($chars)];
     }
     $resp = $resp2 = array();
     $resp['txt_color_st'] = isset($_POST['txt_color_st']) ? Uiform_Form_Helper::sanitizeInput($_POST['txt_color_st']) : '';
     $resp['txt_color'] = isset($_POST['txt_color']) ? Uiform_Form_Helper::sanitizeInput($_POST['txt_color']) : '';
     $resp['background_st'] = isset($_POST['background_st']) ? Uiform_Form_Helper::sanitizeInput($_POST['background_st']) : '';
     $resp['background_color'] = isset($_POST['txt_color_st']) ? Uiform_Form_Helper::sanitizeInput($_POST['background_color']) : '';
     $resp['distortion'] = isset($_POST['distortion']) ? Uiform_Form_Helper::sanitizeInput($_POST['distortion']) : '';
     $resp['behind_lines_st'] = isset($_POST['behind_lines_st']) ? Uiform_Form_Helper::sanitizeInput($_POST['behind_lines_st']) : '';
     $resp['behind_lines'] = isset($_POST['behind_lines']) ? Uiform_Form_Helper::sanitizeInput($_POST['behind_lines']) : '';
     $resp['front_lines_st'] = isset($_POST['front_lines_st']) ? Uiform_Form_Helper::sanitizeInput($_POST['front_lines_st']) : '';
     $resp['front_lines'] = isset($_POST['front_lines']) ? Uiform_Form_Helper::sanitizeInput($_POST['front_lines']) : '';
     $resp['ca_txt_gen'] = $phrase;
     $captcha_options = Uiform_Form_Helper::base64url_encode(json_encode($resp));
     $resp2 = array();
     $resp2['rkver'] = $captcha_options;
     //return data to ajax callback
     header('Content-Type: application/json');
     echo json_encode($resp2);
     wp_die();
 }
Example #15
0
 public function getIndex($location = '')
 {
     $loading_arr = Config::get('loading');
     $loading = $loading_arr[array_rand($loading_arr)];
     View::share('location', $location);
     $this->layout->content = View::make('index', compact('loading'));
 }
Example #16
0
 /**
  * @param \Hynage\ORM\Entity|mixed $default
  * @return null
  */
 public function getRandom($default = null)
 {
     if (!$this->count()) {
         return $default;
     }
     return $this->get(array_rand($this->data), $default);
 }
Example #17
0
 public function run()
 {
     $faker = Faker::create();
     $log = new Stream('php://stdout');
     $log->info('Start ' . __CLASS__);
     /** @var Phalcon\Db\AdapterInterface $database */
     $database = $this->getDI()->get('db');
     $userIds = Users::find(['columns' => 'id'])->toArray();
     $database->begin();
     for ($i = 0; $i <= self::POSTS_TOTAL; $i++) {
         $title = $faker->company;
         $userRandId = array_rand($userIds);
         $posts = new Posts();
         $posts->usersId = $userIds[$userRandId]['id'];
         $posts->type = rand(0, 1) ? 'questions' : 'tips';
         $posts->title = $title;
         $posts->slug = \Phalcon\Tag::friendlyTitle($title);
         $posts->numberViews = rand(5, 100);
         $posts->numberReply = rand(0, 20);
         $posts->content = $faker->text;
         $posts->sticked = 'N';
         $posts->status = 'A';
         $posts->locked = 'N';
         $posts->deleted = 0;
         $posts->acceptedAnswer = 'N';
         if (!$posts->save()) {
             var_dump($posts->getMessages());
             $database->rollback();
             die;
         }
         $log->info('posts: ' . $posts->getTitle());
     }
 }
 /**
  * @brief 위젯의 실행 부분
  *
  * ./widgets/위젯/conf/info.xml 에 선언한 extra_vars를 args로 받는다
  * 결과를 만든후 print가 아니라 return 해주어야 한다
  **/
 function proc($args)
 {
     $banners = array();
     for ($i = 1; $i <= 10; $i++) {
         $array = array();
         foreach (array('url', 'img', 'target') as $type) {
             $key = $type . "_" . $i;
             $array[$type] = $args->{$key};
         }
         if ($array['img']) {
             array_push($banners, $array);
         }
     }
     shuffle($banners);
     $rand_keys = array_rand($banners, 2);
     $widget_info->url_1 = $banners[$rand_keys[0]]['url'];
     $widget_info->img_1 = $banners[$rand_keys[0]]['img'];
     $widget_info->target_1 = $banners[$rand_keys[0]]['target'];
     $widget_info->url_2 = $banners[$rand_keys[1]]['url'];
     $widget_info->img_2 = $banners[$rand_keys[1]]['img'];
     $widget_info->target_2 = $banners[$rand_keys[1]]['target'];
     Context::set('widget_info', $widget_info);
     $tpl_path = sprintf('%sskins/%s', $this->widget_path, $args->skin);
     Context::set('colorset', $args->colorset);
     $tpl_file = 'skin';
     // 위젯 스킨의 템플릿 파일명을 지칭함. 해당 위젯의 스킨 파일은 이 이름을 써야 동작함.
     $oTemplate =& TemplateHandler::getInstance();
     return $oTemplate->compile($tpl_path, $tpl_file);
 }
Example #19
0
File: xcf.php Project: nopticon/mag
 public function __construct()
 {
     $this->path = LIB . 'captcha/';
     $this->data_directory = XFS . XCOR . 'cache/xcf/';
     $images = $fonts = array();
     $fp = @opendir($this->path);
     while (false !== ($file = @readdir($fp))) {
         if (preg_match('#\\.jpg#is', $file)) {
             $images[] = $file;
         }
         if (preg_match('#\\.ttf#is', $file)) {
             $fonts[] = $file;
         }
     }
     @closedir($fp);
     $this->bgimg = $this->path . $images[array_rand($images)];
     $this->ttf_file = $this->path . $fonts[array_rand($fonts)];
     $this->font_size = rand(19, 22);
     $this->image_width = rand(230, 250);
     $this->image_height = rand(40, 100);
     $this->line_color = array("red" => rand(200, 255), "green" => rand(200, 255), "blue" => rand(200, 255));
     $this->line_distance = rand(27, 30);
     $this->text_color = array("red" => rand(0, 200), "green" => rand(0, 200), "blue" => rand(0, 200));
     $this->image_bg_color = array("red" => rand(245, 255), "green" => rand(245, 255), "blue" => rand(245, 255));
     $this->text_x_start = rand(8, 12);
     $this->text_minimum_distance = rand(28, 32);
     $this->text_transparency_percentage = rand(10, 20);
 }
 public function GetSlideshowPics()
 {
     /*
      * Séléction au hasard une photo dans tout les album
      */
     // Liste tout les dossier photo
     $aListFolder = $this->listFile(PICS_PATH);
     foreach ($aListFolder as $iKey => $sPath) {
         if ($sPath[0] != '_') {
             unset($aListFolder[$iKey]);
         }
     }
     // Liste toute les photo d'un dossié au hasard
     $sFolder = $aListFolder[array_rand($aListFolder)];
     $aListPics = $this->listFile(realpath(PICS_PATH . '/' . $sFolder));
     // Renvoie une photo au hasard ainsi que ses dimention
     $aPics = array();
     $sRandomPics = $aListPics[array_rand($aListPics)];
     //$this->controlPics($sFolder, $sRandomPics);
     $aPics['url'] = PICS_HTTP . $sFolder . '/' . $sRandomPics;
     $aDimention = getimagesize($aPics['url']);
     $aPics['width'] = $aDimention[0];
     $aPics['height'] = $aDimention[1];
     return json_encode($aPics);
 }
  public static function split($testname, $variations = array('control'), $user_id = null) {
    $current_variation = null;
    
    if (isset(self::$_splitTestData[$testname])) {
      // if the test variation was set earlier in the same request, return that
      $current_variation = self::$_splitTestData[$testname];
    } else {
      // allow querystring enabling of features
      if (isset($_REQUEST[$testname]) && in_array($_REQUEST[$testname], $variations)) {
        $current_variation = $_REQUEST[$testname];
      } else if (isset($_COOKIE['split_' . $testname]) && !empty($_COOKIE['split_' . $testname]) && in_array($_COOKIE['split_' . $testname], $variations)) {
        // we've got a variation already set from a previous request
        $current_variation = $_COOKIE['split_' . $testname];
      } else {
        // need to set a variation, use the user id if available
        if ($user_id != null && count($variations) > 0) {
          $current_variation = $variations[($user_id % count($variations))];
        } else {
          $current_variation = $variations[array_rand($variations)];
		    }
      }
      
      // the next two lines should only happen once per request.
      // set (or reset) a short-lived cookie so we don't have to worry about cleaning up old tests
      // when the test code is pulled out, the cookie will expire shortly thereafter
      setcookie('split_' . $testname, $current_variation, time() + (60 * 60 * 24 * 14), '/');
      
      // store the value in case it's needed later in this request
      self::$_splitTestData[$testname] = $current_variation;
    }
    
    // return the current variation
    return $current_variation;
  }
Example #22
0
 /**
  * Test enable/disable of countries.
  */
 public function testCountryUI()
 {
     $this->drupalLogin($this->drupalCreateUser(array('administer countries', 'administer store')));
     // Testing all countries is too much, so we just enable a random selection
     // of 8 countries. All countries will then be tested at some point.
     $countries = \Drupal::service('country_manager')->getAvailableList();
     $country_ids = array_rand($countries, 8);
     $last_country = array_pop($country_ids);
     // Loop over the first seven.
     foreach ($country_ids as $country_id) {
         // Verify this country isn't already enabled.
         $this->drupalGet('admin/store/config/country');
         $this->assertLinkByHref('admin/store/config/country/' . $country_id . '/enable', 0, SafeMarkup::format('%country is not enabled by default.', ['%country' => $countries[$country_id]]));
         // Enable this country.
         $this->drupalGet('admin/store/config/country/' . $country_id . '/enable');
         $this->assertText(t('The country @country has been enabled.', ['@country' => $countries[$country_id]]));
         $this->assertLinkByHref('admin/store/config/country/' . $country_id . '/disable', 0, SafeMarkup::format('%country is now enabled.', ['%country' => $countries[$country_id]]));
     }
     // Verify that last random country doesn't show up as available.
     $this->drupalGet('admin/store/config/store');
     $this->assertNoOption('edit-uc-store-country', $last_country, SafeMarkup::format('%country not listed in uc_address select country field.', ['%country' => $countries[$last_country]]));
     // Enable the last country.
     $this->drupalGet('admin/store/config/country/' . $last_country . '/enable');
     $this->assertText(t('The country @country has been enabled.', ['@country' => $countries[$last_country]]));
     $this->assertLinkByHref('admin/store/config/country/' . $last_country . '/disable', 0, SafeMarkup::format('%country is now enabled.', ['%country' => $countries[$last_country]]));
     // Verify that last random country now shows up as available.
     $this->drupalGet('admin/store/config/store');
     $this->assertOption('edit-uc-store-country', $last_country, SafeMarkup::format('%country is listed in uc_address select country field.', ['%country' => $countries[$last_country]]));
     // Disable the last country using the operations button.
     $this->drupalGet('admin/store/config/country');
     $this->clickLink('Disable', 7);
     // The 8th Disable link.
     $this->assertText(t('The country @country has been disabled.', ['@country' => $countries[$last_country]]));
     $this->assertLinkByHref('admin/store/config/country/' . $last_country . '/enable', 0, SafeMarkup::format('%country is now disabled.', ['%country' => $countries[$last_country]]));
 }
 public function reply($user, $message)
 {
     $message = $this->prepareMessage($message);
     $this->storeInput($message);
     $triggers = $this->tree['topics'][$this->getMetadata('topic')]['triggers'];
     if (count($triggers) > 0) {
         foreach ($triggers as $key => $trigger) {
             foreach ($this->triggers as $class) {
                 $triggerClass = "\\Vulcan\\Rivescript\\Triggers\\{$class}";
                 $triggerClass = new $triggerClass();
                 $found = $triggerClass->parse($key, $trigger['trigger'], $message);
                 if (isset($found['match']) and $found['match'] === true) {
                     log_debug('Found match', ['type' => $class, 'message' => $message, 'found' => $found]);
                     break 2;
                 }
             }
         }
         if (isset($found['key']) and is_int($found['key'])) {
             $replies = $triggers[$found['key']]['reply'];
             if (isset($triggers[$found['key']]['redirect'])) {
                 return $this->reply($user, $triggers[$found['key']]['redirect']);
             }
             if (count($replies)) {
                 $key = array_rand($replies);
                 $reply = $this->parseReply($replies[$key], $found['data']);
                 return $reply;
             }
         }
     }
     return 'No response found.';
 }
Example #24
0
function getRandomFromArray($ar)
{
    mt_srand((double) microtime() * 1000000);
    // php 4.2+ not needed
    $num = array_rand($ar);
    return $ar[$num];
}
 public function getRandGlassBreak()
 {
     for ($i = 0; $i < 10000; ++$i) {
         $this->state[] = $i;
     }
     return array_rand($this->state);
 }
 public function crossover()
 {
     $new_population = array();
     for ($i = 0; $i < $this->options['population']; $i++) {
         // get random parents
         $a = $this->population[array_rand($this->population, 1)]['chromosome'];
         $b = $this->population[array_rand($this->population, 1)]['chromosome'];
         $goal = $this->options['goal'];
         $a = str_split($a);
         $b = str_split($b);
         $goal = str_split($goal);
         // get the best chromosome otherwise random from parents
         $child = '';
         for ($j = 0; $j < count($a); $j++) {
             if ($a[$j] == $goal[$j]) {
                 $child .= $a[$j];
             } elseif ($b[$j] == $goal[$j]) {
                 $child .= $b[$j];
             } else {
                 $child .= rand(0, 1) == 0 ? $a[$j] : $b[$j];
             }
         }
         $new_population[] = array('chromosome' => $child, 'fitness' => 0);
     }
     $this->population = $new_population;
 }
Example #27
0
 public function index()
 {
     $colors = array('007AFF', 'FF7000', 'FF7000', '15E25F', 'CFC700', 'CFC700', 'CF1100', 'CF00BE', 'F00');
     $userColor = array_rand($colors);
     $this->smarty->assign('user_color', $colors[$userColor]);
     $this->view('ws/test');
 }
Example #28
0
 /**
  * Get a singleton Database instance. If configuration is not specified,
  * it will be loaded from the database configuration file using the same
  * group as the name.
  *
  *     // Load the default database
  *     $db = static::instance();
  *
  *     // Create a custom configured instance
  *     $db = static::instance('custom', $config);
  *
  * @param   string $name     instance name
  * @param   array  $config   configuration parameters
  * @param   bool   $writable when replication is enabled, whether to return the master connection
  *
  * @return  Database_Connection
  *
  * @throws \FuelException
  */
 public static function instance($name = null, array $config = null, $writable = true)
 {
     \Config::load('db', true);
     if ($name === null) {
         // Use the default instance name
         $name = \Config::get('db.active');
     }
     if (!$writable and $readonly = \Config::get("db.{$name}.readonly", false)) {
         !isset(static::$_readonly[$name]) and static::$_readonly[$name] = \Arr::get($readonly, array_rand($readonly));
         $name = static::$_readonly[$name];
     }
     if (!isset(static::$instances[$name])) {
         if ($config === null) {
             // Load the configuration for this database
             $config = \Config::get("db.{$name}");
         }
         if (!isset($config['type'])) {
             throw new \FuelException('Database type not defined in "{$name}" configuration or "{$name}" configuration does not exist');
         }
         // Set the driver class name
         $driver = '\\Database_' . ucfirst($config['type']) . '_Connection';
         // Create the database connection instance
         new $driver($name, $config);
     }
     return static::$instances[$name];
 }
Example #29
0
 /**
  * Randomly pick one mailbox store from all available stores
  *
  * @return		Object		A single matched object from the original resultset
  */
 public function pick()
 {
     $result = $this->result instanceof \ADX\Core\Result ? $this->result : $this->all();
     $item = array_rand($result->to_array());
     // Randomly pick one item from the array
     return $result[$item];
 }
Example #30
0
 public function randomArrayKey(array $arr)
 {
     if (!$arr) {
         return null;
     }
     return array_rand($arr);
 }