Ejemplo n.º 1
0
 function get()
 {
     $aim_table = I('aim_table');
     $aim_id = I('aim_id');
     $list = D('Comment')->getComment($aim_id, $aim_table);
     if ($list == null) {
         $list = array();
     }
     $sensitiveStr = C('SENSITIVE_WORDS');
     $sensitiveArr = explode(',', $sensitiveStr);
     $badkeywords = array_combine($sensitiveArr, array_fill(0, count($sensitiveArr), '***'));
     foreach ($badkeywords as $k => &$v) {
         // if (mb_strlen ( $k, 'utf8' ) <= 2) {
         // unset ( $badkeywords [$k] );
         // }
         if (empty($k)) {
             unset($badkeywords[$k]);
         }
     }
     foreach ($list as &$v) {
         $v['content'] = strtr($v['content'], $badkeywords);
         $v['content'] = parseComment($v['content']);
         $v['time'] = time_format($v['cTime']);
         // dump($v['content']);
     }
     // dump($list);
     $this->ajaxReturn($list, 'JSON');
 }
 /**
  * Interpolate values in a matrice so that the total number of data points
  * in vert and horizontal axis are $aIntNbr more. For example $aIntNbr=2 will
  * make the data matrice have tiwce as many vertical and horizontal dta points.
  *
  * Note: This will blow up the matrcide in memory size in the order of $aInNbr^2
  *
  * @param  $ &$aData The original data matricde
  * @param  $aInNbr Interpolation factor
  * @return the interpolated matrice
  */
 function Linear(&$aData, $aIntFactor)
 {
     $step = pow(2, $aIntFactor - 1);
     $orig_cols = count($aData[0]);
     $orig_rows = count($aData);
     // Number of new columns/rows
     // N = (a-1) * 2^(f-1) + 1
     $p = pow(2, $aIntFactor - 1);
     $new_cols = $p * ($orig_cols - 1) + 1;
     $new_rows = $p * ($orig_rows - 1) + 1;
     $this->data = array_fill(0, $new_rows, array_fill(0, $new_cols, 0));
     // Initialize the new matrix with the values that we know
     for ($i = 0; $i < $new_rows; $i++) {
         for ($j = 0; $j < $new_cols; $j++) {
             $v = 0;
             if ($i % $step == 0 && $j % $step == 0) {
                 $v = $aData[$i / $step][$j / $step];
             }
             $this->data[$i][$j] = $v;
         }
     }
     for ($i = 0; $i < $new_rows - 1; $i += $step) {
         for ($j = 0; $j < $new_cols - 1; $j += $step) {
             $this->IntSquare($i, $j, $aIntFactor);
         }
     }
     return $this->data;
 }
Ejemplo n.º 3
0
 /**
  * Creates a new Salsa20 instance
  *
  * @param  string $key (32 bytes)
  * @param  string $iv (8 bytes)
  */
 public function __construct($key, $iv)
 {
     $this->useKey($key);
     $this->useIv($iv);
     $this->position = self::OUTPUT_LEN;
     $this->output = array_fill(0, self::OUTPUT_LEN, 0);
 }
Ejemplo n.º 4
0
 public function save()
 {
     $values = get_object_vars($this);
     $filtered = null;
     foreach ($values as $key => $value) {
         if ($value !== null && $value !== '' && strpos($key, 'obj_') === false && $key !== 'id') {
             if ($value === false) {
                 $value = 0;
             }
             $filtered[$key] = $value;
         }
     }
     $columns = array_keys($filtered);
     if ($this->id) {
         $columns = join(" = ?, ", $columns);
         $columns .= ' = ?';
         $query = "UPDATE " . static::$table . " SET {$columns} WHERE id =" . $this->id;
     } else {
         $params = join(", ", array_fill(0, count($columns), "?"));
         $columns = join(", ", $columns);
         $query = "INSERT INTO " . static::$table . " ({$columns}) VALUES ({$params})";
     }
     $result = self::$database->execute($query, null, $filtered);
     if ($result) {
         $result = array('error' => false, 'message' => self::$database->getInsertedID());
     } else {
         $result = array('error' => true, 'message' => self::$database->getError());
     }
     return $result;
 }
Ejemplo n.º 5
0
 public function run()
 {
     $this->requireDataset('Huge');
     $doc = array('key' => str_repeat("var", 1000));
     $docs = array_fill(0, 5000, $doc);
     // Test 1: Retrieve only the first 100 results. Then delete the cursor. This should trigger a stop message.
     $cursor = r\db('Huge')->table('t5000')->without('id')->run($this->conn);
     $i = 0;
     foreach ($cursor as $val) {
         if (!$this->compareArrays($doc, $val)) {
             echo "Read wrong value.\n";
         }
         if ($i++ >= 100) {
             break;
         }
     }
     unset($cursor);
     // Test 2: Call the cursor's close() method. The cursor should not return any more rows.
     $cursor = r\db('Huge')->table('t5000')->without('id')->run($this->conn);
     $cursor->close();
     if (!$this->compareArrays(array(), $cursor->toArray())) {
         echo "Cursor still returned results after it was closed.\n";
     }
     // Test 3: Retrieve all results. This tests paging.
     $this->checkQueryResult(r\db('Huge')->table('t5000')->without('id'), $docs);
 }
Ejemplo n.º 6
0
 /**
  * @param int $level
  * @return string[]
  */
 private function getLevelPaths($level)
 {
     if ($level) {
         return array_fill(0, $level, '..');
     }
     return array();
 }
Ejemplo n.º 7
0
 public function create()
 {
     $key = $this->getPrimary();
     //if it does exists, then update, else insert
     if ($this->exists()) {
         $this->update();
         return $this->{$key};
     } else {
         #####################################
         $columnstmp = $this->getColumns();
         foreach ($columnstmp as $colname) {
             $columns[$colname] = $this->{$colname};
         }
         $table = $this->getTable();
         $qmarks = array_fill(0, count($columns), '?');
         $sql = "INSERT INTO {$table} (" . join(',', array_keys($columns)) . ") VALUES(" . join(',', $qmarks) . ")";
         $columns = array_values($columns);
         //values must be integer indexed array
         $database = SomeFactory::getDBO();
         $statement = $database->prepare($sql);
         $this->sql = $sql;
         $success = $statement->execute($columns);
         ob_start();
         print_r($columns);
         $this->columnsdebug = ob_get_clean();
         return $this->{$key};
         #####################################
     }
 }
 /**
  * Builds a Doctrine query with processed values
  * 
  * @param   array   $values Values
  * @return  Doctrine_Query
  * @author  relo_san
  * @since   february 17, 2010
  */
 protected function doBuildQuery(array $values)
 {
     $query = isset($this->options['query']) ? clone $this->options['query'] : $this->getTable()->createQuery('r');
     if ($method = $this->getTableMethod()) {
         $query = $this->getTable()->{$method}($query);
     }
     $fields = $this->getFields();
     $names = array_merge($fields, array_diff(array_keys($this->validatorSchema->getFields()), array_keys($fields)));
     $fields = array_merge($fields, array_combine($names, array_fill(0, count($names), null)));
     foreach ($fields as $field => $type) {
         if (!isset($values[$field]) || null === $values[$field] || '' === $values[$field]) {
             continue;
         }
         $method = sprintf('add%sColumnQuery', self::camelize($this->getFieldName($field)));
         if (method_exists($this, $method)) {
             $this->{$method}($query, $field, $values[$field]);
         } else {
             if (null !== $type) {
                 if (!method_exists($this, $method = sprintf('add%sQuery', $type))) {
                     throw new LogicException(sprintf('Unable to filter for the "%s" type.', $type));
                 }
                 $this->{$method}($query, $field, $values[$field]);
             }
         }
     }
     return $query;
 }
 /**
  * {@inheritdoc}
  *
  * @override
  * @internal Order of the parameters must be the same as the order of the columns in
  *           _getInsertRowSql.
  */
 protected function _getInsertRowSQL(PersistentCollection $coll)
 {
     $mapping = $coll->getMapping();
     $joinTable = $mapping['joinTable'];
     $columns = $mapping['joinTableColumns'];
     return 'INSERT INTO ' . $joinTable['name'] . ' (' . implode(', ', $columns) . ')' . ' VALUES (' . implode(', ', array_fill(0, count($columns), '?')) . ')';
 }
Ejemplo n.º 10
0
 private function _build_where_clause($query)
 {
     if (!$query->where) {
         return;
     }
     $where = $where_params = [];
     $param_count = 0;
     foreach ($query->where as $condition) {
         # Case: ["foo" => $foo, "bar" => $bar];
         if (is_array($condition)) {
             foreach ($condition as $column => $value) {
                 $where[] = '`' . $column . '` = ?';
                 $where_params[] = $value;
             }
         } else {
             if ($count = substr_count($condition, '?')) {
                 foreach (range(0, $count - 1) as $i) {
                     if (!isset($query->where_params[$param_count])) {
                         throw new Exception\RuntimeException(sprintf("Value for question mark placeholder for WHERE clause part wasn't found (%s)", $condition));
                     }
                     if (is_array($query->where_params[$param_count])) {
                         $condition = preg_replace('/\\?/', implode(', ', array_fill(0, count($query->where_params[$param_count]), '?')), $condition, 1);
                     }
                     $where_params[] = $query->where_params[$param_count];
                     $param_count++;
                 }
             } elseif ($count = substr_count($condition, ':')) {
                 $where_params = $query->where_params;
             }
             $where[] = $condition;
         }
     }
     return [implode(' AND ', $where), $where_params];
 }
Ejemplo n.º 11
0
 public static function combineArrayWithSingleElement($keys, $var)
 {
     if (empty($keys)) {
         return array();
     }
     return array_combine($keys, array_fill(0, count($keys), $var));
 }
Ejemplo n.º 12
0
 public function get($key)
 {
     $sql = 'SELECT k_key, k_value FROM ' . $this->_connection->prefixTable($this->table) . ' WHERE k_expire > \'' . date('Y-m-d H:i:s') . '\' AND k_key ';
     if (is_array($key)) {
         $in = '';
         foreach ($key as $k) {
             $in .= ',' . $this->_connection->quote($k);
         }
         $sql .= ' IN (' . substr($in, 1) . ')';
         $result = array_combine($key, array_fill(0, count($key), null));
         $rs = $this->_connection->query($sql);
         if (!$rs) {
             return $result;
         }
         foreach ($rs as $rec) {
             $result[$rec->k_key] = unserialize($rs->unescapeBin($rec->k_value));
         }
         return $result;
     } else {
         $sql .= ' = ' . $this->_connection->quote($key);
         $rs = $this->_connection->query($sql);
         if (!$rs) {
             return null;
         }
         $result = $rs->fetch();
         if (!$result) {
             return null;
         }
         return unserialize($rs->unescapeBin($result->k_value));
     }
 }
Ejemplo n.º 13
0
 public function test_getWordSets()
 {
     // given an array of arrays like
     // array( array('a','b'), array('c','d') )
     // returns a summary as string: '(a|b),(c|d)'
     function serialize_sets($aSets)
     {
         $aParts = array();
         foreach ($aSets as $aSet) {
             $aParts[] = '(' . join('|', $aSet) . ')';
         }
         return join(',', $aParts);
     }
     $this->assertEquals(array(array('')), getWordSets(array(), 0));
     $this->assertEquals('(a)', serialize_sets(getWordSets(array("a"), 0)));
     $this->assertEquals('(a b),(a|b)', serialize_sets(getWordSets(array('a', 'b'), 0)));
     $this->assertEquals('(a b c),(a|b c),(a|b|c),(a b|c)', serialize_sets(getWordSets(array('a', 'b', 'c'), 0)));
     $this->assertEquals('(a b c d),(a|b c d),(a|b|c d),(a|b|c|d),(a|b c|d),(a b|c d),(a b|c|d),(a b c|d)', serialize_sets(getWordSets(array('a', 'b', 'c', 'd'), 0)));
     // Inverse
     $this->assertEquals('(a b c),(c|a b),(c|b|a),(b c|a)', serialize_sets(getInverseWordSets(array('a', 'b', 'c'), 0)));
     // make sure we don't create too many sets
     // 4 words => 8 sets
     // 10 words => 511 sets
     // 15 words => 12911 sets
     // 18 words => 65536 sets
     // 20 words => 169766 sets
     // 22 words => 401930 sets
     // 28 words => 3505699 sets (needs more than 4GB via 'phpunit -d memory_limit=' to run)
     $this->assertEquals(8, count(getWordSets(array_fill(0, 4, 'a'), 0)));
     $this->assertEquals(65536, count(getWordSets(array_fill(0, 18, 'a'), 0)));
 }
Ejemplo n.º 14
0
 public function replace($content, $replace = '*')
 {
     // 计算文本内容长度
     $cLength = mb_strlen($content, 'UTF-8');
     $words = array();
     // 对每个字符进行关键词检查
     for ($i = 0; $i < $cLength; $i++) {
         $words[] = mb_substr($content, $i, 1, 'UTF-8');
     }
     // 对每个字符进行关键词检查
     foreach ($words as $i => $word) {
         // 首字符是否在过滤关键词分类中存在
         if (isset($this->classArr[$word])) {
             // 如果存在则将该分类下的所有关键词遍历,依次对文本内容中与每一个关键词位置长度相对应的字符串进行比较
             foreach ($this->classArr[$word] as $v) {
                 // 过滤关键词长度
                 $filterWordLength = mb_strlen($v, 'UTF-8');
                 // 获取文本中对应位置,相同长度的字符串
                 $contentEqPostionWord = mb_substr($content, $i, $filterWordLength, 'UTF-8');
                 // 对两个字符串进行比较
                 if ($contentEqPostionWord == $v) {
                     // 如果相同,则将该段字符串替换成相应长度的 *
                     array_splice($words, $i, $filterWordLength, array_fill(0, $filterWordLength, $replace));
                 }
             }
         }
     }
     return implode('', $words);
 }
Ejemplo n.º 15
0
 public function Calculate($str1, $str2)
 {
     $this->str1 = $str1;
     $this->str2 = $str2;
     $this->c = array_fill(0, strlen($str1), array_fill(0, strlen($str2), array()));
     $this->b = array_fill(0, strlen($str2), array_fill(0, strlen($str2), array()));
     $this->commonString = '';
     $this->length = 0;
     $str1_len = strlen($this->str1);
     $str2_len = strlen($this->str2);
     for ($i = 1; $i <= $str1_len; $i++) {
         $this->c[$i][0] = 0;
     }
     for ($j = 0; $j <= $str2_len; $j++) {
         $this->c[0][$j] = 0;
     }
     for ($i = 1; $i <= $str1_len; $i++) {
         for ($j = 1; $j <= $str2_len; $j++) {
             if (substr($this->str1, $i, 1) == substr($this->str2, $j, 1)) {
                 $this->c[$i][$j] = $this->c[$i - 1][$j - 1] + 1;
                 $this->b[$i][$j] = 'TOP_LEFT';
             } else {
                 $this->c[$i][$j] = $this->c[$i - 1][$j] >= $this->c[$i][$j - 1] ? $this->c[$i - 1][$j] : $this->c[$i][$j - 1];
                 $this->b[$i][$j] = $this->c[$i - 1][$j] >= $this->c[$i][$j - 1] ? 'TOP' : 'LEFT';
             }
         }
     }
     $this->generateCommonString(strlen($this->str1), strlen($this->str2));
     $this->length = strlen($this->commonString);
 }
Ejemplo n.º 16
0
 /**
  * Quick insert record
  * @param $table
  * @param array $columnData
  * @return \Doctrine\DBAL\Driver\Statement
  */
 public function insert($table, array $columnData)
 {
     $columns = array_keys($columnData);
     $sql = sprintf("INSERT INTO %s (%s) VALUES (%s);", $table, implode(', ', $columns), implode(', ', array_fill(0, count($columnData), '?')));
     $this->db->executeQuery($sql, array_values($columnData));
     return $this->db->lastInsertId($table);
 }
 public function solution($A)
 {
     $N = count($A);
     $numberOfIntersectingDiscs = 0;
     $numberOfDiscsStartedAt = array_fill(0, $N, 0);
     $numberOfDiscsEndedAt = array_fill(0, $N, 0);
     for ($i = 0; $i < $N; $i++) {
         $startingIndex = $i - $A[$i] > 0 ? $i - $A[$i] : 0;
         $endingIndex = $i + $A[$i] < $N - 1 ? $i + $A[$i] : $N - 1;
         $numberOfDiscsStartedAt[$startingIndex]++;
         $numberOfDiscsEndedAt[$endingIndex]++;
     }
     $discsAtCurrentPosition = 0;
     for ($i = 0; $i < $N; $i++) {
         if ($numberOfDiscsStartedAt[$i] > 0) {
             $numberOfIntersectingDiscs += $discsAtCurrentPosition * $numberOfDiscsStartedAt[$i];
             $numberOfIntersectingDiscs += $numberOfDiscsStartedAt[$i] * ($numberOfDiscsStartedAt[$i] - 1) / 2;
             if ($numberOfIntersectingDiscs > 10000000) {
                 return -1;
             }
             $discsAtCurrentPosition += $numberOfDiscsStartedAt[$i];
         }
         $discsAtCurrentPosition -= $numberOfDiscsEndedAt[$i];
     }
     return $numberOfIntersectingDiscs;
 }
Ejemplo n.º 18
0
 /**
  * Compile an insert statement into SQL.
  *
  * @param  Illuminate\Database\Query\Builder  $query
  * @param  array  $values
  * @return string
  */
 public function compileInsert(Builder $query, array $values)
 {
     // Essentially we will force every insert to be treated as a batch insert which
     // simply makes creating the SQL easier for us since we can utilize the same
     // basic routine regardless of an amount of records given to us to insert.
     $table = $this->wrapTable($query->from);
     if (!is_array(reset($values))) {
         $values = array($values);
     }
     // If there is only one record being inserted, we will just use the usual query
     // grammar insert builder because no special syntax is needed for the single
     // row inserts in SQLite. However, if there are multiples, we'll continue.
     if (count($values) == 1) {
         return parent::compileInsert($query, $values[0]);
     }
     $names = $this->columnize(array_keys($values[0]));
     $columns = array();
     // SQLite requires us to build the multi-row insert as a listing of select with
     // unions joining them together. So we'll build out this list of columns and
     // then join them all together with select unions to complete the queries.
     foreach (array_keys($values[0]) as $column) {
         $columns[] = '? as ' . $this->wrap($column);
     }
     $columns = array_fill(9, count($values), implode(', ', $columns));
     return "insert into {$table} ({$names}) select " . implode(' union select ', $columns);
 }
 /**
  * Birthday spacings: Choose random points on a large interval. 
  * The spacings between the points should be asymptotically exponentially
  * distributed.
  */
 public function testBirthday()
 {
     // Number of buckets to make
     $num_buckets = 17;
     // How much tolerance should we allow? 0.01 = 1% 0.50 = 50%, etc.
     $tolerance = 0.03;
     $rand_min = 200000;
     $rand_max = 600000;
     $rand_step = 100000;
     $minT = 1.0 - $tolerance;
     $maxT = 1.0 + $tolerance;
     for ($nums_to_generate = $rand_min; $nums_to_generate < $rand_max; $nums_to_generate += $rand_step) {
         $buckets = array_fill(0, $num_buckets, 0);
         // The number of ints we expect per bucket +/- 2%;
         $min = (int) ceil($minT * $nums_to_generate / $num_buckets);
         $max = (int) floor($maxT * $nums_to_generate / $num_buckets);
         for ($i = 0; $i < $nums_to_generate; ++$i) {
             $random = random_int(0, 999);
             $bucket = $random % $num_buckets;
             $buckets[$bucket]++;
         }
         for ($i = 0; $i < $num_buckets; ++$i) {
             // Debugging code:
             if ($buckets[$i] <= $min) {
                 var_dump(['bucket' => $i, 'value' => $buckets[$i], 'min' => $min, 'nums' => $nums_to_generate, 'reason' => 'below min']);
             }
             if ($buckets[$i] >= $max) {
                 var_dump(['bucket' => $i, 'value' => $buckets[$i], 'maax' => $max, 'nums' => $nums_to_generate, 'reason' => 'above max']);
             }
             $this->assertTrue($buckets[$i] < $max && $buckets[$i] > $min);
         }
     }
 }
Ejemplo n.º 20
0
 /**
  * insert row.
  *
  * @return string last insert id, if row was created or null on failure.
  */
 public function create()
 {
     //get the fields. unset primary key
     $columnstmp = $this->getColumns();
     foreach ($columnstmp as $colname) {
         $columns[$colname] = $this->{$colname};
     }
     $key = $this->getPrimary();
     $table = $this->getTable();
     $qmarks = array_fill(0, count($columns) - 1, '?');
     array_shift($columns);
     //get the primary key away, it is first column
     $sql = "INSERT INTO {$table} (" . join(',', array_keys($columns)) . ") VALUES(" . join(',', $qmarks) . ")";
     $columns = array_values($columns);
     //values must be integer indexed array
     $database = SomeFactory::getDBO();
     $statement = $database->prepare($sql);
     $this->sql = $sql;
     $success = $statement->execute($columns);
     ob_start();
     print_r($columns);
     $this->columnsdebug = ob_get_clean();
     $id = $database->lastInsertId("{$table}_id_seq");
     #$dberrs = $database->errorInfo();
     #	var_dump($this->sql,$columns, $id,$dberrs); exit;
     /*
     	   if (!$id) {
     			$dberrs = $database->errorInfo();
     			var_dump($dberrs); exit;
     			throw new SomeDatabaseException( $dberrs[2]);
     		}*/
     $this->{$key} = $id;
     //debug
     return $id;
 }
Ejemplo n.º 21
0
 /**
  * Delete meta keys
  *
  * @global type $wpdb
  * @param type $keys
  * @param type $post_id
  * @return type
  */
 static function delete_meta_key($keys, $post_id = null)
 {
     if (empty($keys) || !count($keys)) {
         return false;
     }
     global $wpdb;
     $extra = !empty($post_id) ? 'post_id = ' . esc_sql($post_id) . ' AND' : '';
     $sql = "DELETE FROM {$wpdb->postmeta} WHERE {$extra} meta_key IN (" . implode(', ', array_fill(0, count($keys), '%s')) . ")";
     // Call $wpdb->prepare passing the values of the array as separate arguments
     $query = call_user_func_array(array($wpdb, 'prepare'), array_merge(array($sql), $keys));
     $wpdb->query($query);
     // del all blog
     if (is_network_admin()) {
         // get list id blog all
         $list_prefix_musite = $wpdb->get_results("SELECT blog_id FROM {$wpdb->blogs}", ARRAY_A);
         if ($list_prefix_musite && count($list_prefix_musite) > 1) {
             foreach ($list_prefix_musite as $key => $value) {
                 if ($value['blog_id'] == 1) {
                     continue;
                 }
                 $prefix = $wpdb->prefix . $value['blog_id'] . '_';
                 $sql = "DELETE FROM {$prefix}postmeta WHERE {$extra} meta_key IN (" . implode(', ', array_fill(0, count($keys), '%s')) . ")";
                 // Call $wpdb->prepare passing the values of the array as separate arguments
                 $query = call_user_func_array(array($wpdb, 'prepare'), array_merge(array($sql), $keys));
                 $wpdb->query($query);
             }
         }
     }
 }
Ejemplo n.º 22
0
 public function solution($A)
 {
     $N = count($A);
     if ($N <= 2) {
         return 0;
     }
     $sum = array_fill(0, $N, 0);
     for ($i = 1; $i < $N; $i++) {
         $sum[$i] = $sum[$i - 1];
         if ($A[$i] > $A[$i - 1] && $A[$i] > $A[$i + 1]) {
             $sum[$i]++;
         }
     }
     $sum[$N - 1] = $sum[$N - 2];
     $func = function ($sum = [], $m) {
         if ($sum[$m - 1] <= 0) {
             return false;
         }
         $length = count($sum);
         for ($i = 2; $i <= $length / $m; $i++) {
             if ($sum[$i * $m - 1] - $sum[$i * $m - $m - 1] <= 0) {
                 return false;
             }
         }
         return true;
     };
     for ($i = 1; $i <= $N; $i++) {
         if ($N % $i == 0 && $func($sum, $i)) {
             return $N / $i;
         }
     }
     return 0;
 }
Ejemplo n.º 23
0
 static function tagSql($tag)
 {
     $tagCount = count($tag);
     $tagHolders = implode(',', array_fill(0, $tagCount, '?'));
     $sql = "\n\t\tWHERE EXISTS (\n\t\t\tSELECT `articleid`, count(1) AS counts FROM `pache_tag`\n\t\t\tWHERE tagname IN ( {$tagHolders} )\n\t\t\tAND `pache_article`.id = articleid\n\t\t\tHAVING counts = {$tagCount}\n\t\t)\n\t\t";
     return $sql;
 }
Ejemplo n.º 24
0
 protected function buildOperationQuery(PHPUnit_Extensions_Database_DataSet_ITableMetaData $databaseTableMetaData, PHPUnit_Extensions_Database_DataSet_ITable $table)
 {
     $columns = implode(', ', $table->getTableMetaData()->getColumns());
     $placeHolders = implode(', ', array_fill(0, count($table->getTableMetaData()->getColumns()), '?'));
     $query = "\n            INSERT INTO {$table->getTableMetaData()->getTableName()}\n            ({$columns})\n            VALUES\n            ({$placeHolders})\n        ";
     return $query;
 }
 /**
  * @internal
  */
 public static function _admin_action_get_ajax_response()
 {
     /**
      * @var WPDB $wpdb
      */
     global $wpdb;
     $type = FW_Request::POST('data/type');
     $names = json_decode(FW_Request::POST('data/names'), true);
     $title = FW_Request::POST('data/string');
     $items = array();
     switch ($type) {
         case 'posts':
             $items = $wpdb->get_results(call_user_func_array(array($wpdb, 'prepare'), array_merge(array("SELECT ID val, post_title title " . "FROM {$wpdb->posts} " . "WHERE post_title LIKE %s " . "AND post_status IN ( 'publish', 'private' ) " . "AND post_type IN ( " . implode(', ', array_fill(1, count($names), '%s')) . " ) " . "LIMIT 100", '%' . $wpdb->esc_like($title) . '%'), $names)));
             break;
         case 'taxonomy':
             $items = $wpdb->get_results(call_user_func_array(array($wpdb, 'prepare'), array_merge(array("SELECT terms.term_id val, terms.name title " . "FROM {$wpdb->terms} as terms, {$wpdb->term_taxonomy} as taxonomies " . "WHERE terms.name LIKE %s AND taxonomies.taxonomy IN ( " . implode(', ', array_fill(1, count($names), '%s')) . " ) " . "AND terms.term_id = taxonomies.term_id " . "AND taxonomies.term_id = taxonomies.term_taxonomy_id " . "LIMIT 100", '%' . $wpdb->esc_like($title) . '%'), $names)));
             break;
         case 'users':
             if (empty($names)) {
                 $items = $wpdb->get_results($wpdb->prepare("SELECT users.id val, users.user_nicename title " . "FROM {$wpdb->users} as users " . "WHERE users.user_nicename LIKE %s " . "LIMIT 100", '%' . $wpdb->esc_like($title) . '%'));
             } else {
                 $like_user_meta = array();
                 foreach ($names as $name) {
                     $like_user_meta[] = '%' . $wpdb->esc_like($name) . '%';
                 }
                 $items = $wpdb->get_results(call_user_func_array(array($wpdb, 'prepare'), array_merge(array("SELECT users.id val, users.user_nicename title " . "FROM {$wpdb->users} as users, {$wpdb->usermeta} as usermeta " . "WHERE users.user_nicename LIKE %s AND usermeta.meta_key = 'wp_capabilities' " . "AND ( " . implode(' OR ', array_fill(1, count($like_user_meta), 'usermeta.meta_value LIKE %s')) . " ) " . "AND usermeta.user_id = users.ID", '%' . $wpdb->esc_like($title) . '%'), $like_user_meta)));
             }
             break;
     }
     wp_send_json_success($items);
 }
Ejemplo n.º 26
0
 /**
  * Construct Hidden Markov Model froms set of labels
  * 
  * @param int $states 
  * @param array $labels 
  * @return void
  */
 public function __construct($states, array $labels)
 {
     $this->labels = array_values($labels);
     $this->start = array_fill(0, $states, 1 / $states);
     $this->transistion = array_fill(0, $states, array_fill(0, $states, 1 / $states));
     $this->emission = array_fill(0, $states, array_fill(0, count($labels), 1 / count($labels)));
 }
Ejemplo n.º 27
0
 /**
  * @dataProvider dataProvider
  */
 public function testProcess($number, $limit, $expected)
 {
     $processor = new LimitProcessor($limit);
     $items = array_fill(0, $number, new Item());
     $items = $processor->process($items);
     $this->assertCount($expected, $items);
 }
Ejemplo n.º 28
0
 /**
  * @param $obj
  * @param $methods
  * @return array
  */
 public function parseArguments($obj = NULL)
 {
     if ($this->getArguments()) {
         $arguments = explode('.', $this->getArguments());
         foreach ($arguments as $key => $value) {
             if ($value === 'NULL' || is_null($value)) {
                 $arguments[$key] = array(NULL);
             } elseif ($value === 'this') {
                 $arguments[$key] = array($obj);
             } else {
                 $arguments[$key] = explode(',', $arguments[$key]);
                 foreach ($arguments[$key] as $k => $a) {
                     if ($a === 'NULL') {
                         $arguments[$key][$k] = NULL;
                     } elseif ($a === 'this') {
                         $arguments[$key][$k] = $obj;
                     }
                 }
             }
         }
     } else {
         $arguments = array_fill(0, count($this->parseMethods()), array(NULL));
     }
     return $arguments;
 }
Ejemplo n.º 29
0
 /**
  * Get sum in words
  * @param int $amount Amount of objects (0 <= amount <= PHP_INT_MAX)
  * @param int $gender Gender of object (MALE, FEMALE or NEUTER)
  * @param array $variants Variants (forms) of object in such form: array('1 object', '2 objects', '5 objects')
  * @return string In-words representation objects' amount
  * @throws \RangeException
  * @throws \InvalidArgumentException
  */
 public function sumString($amount, $gender, array $variants = null)
 {
     if ($variants === null) {
         $variants = array_fill(0, 3, '');
     }
     if (sizeof($variants) < 3) {
         throw new \InvalidArgumentException('Incorrect items length (must be 3)');
     }
     if ($amount < 0) {
         throw new \InvalidArgumentException('Amount must be positive or 0');
     }
     if ($amount == 0) {
         return trim('ноль ' . $variants[2]);
     }
     $result = '';
     $tmpVal = $amount;
     //ones
     list($result, $tmpVal) = $this->_sumStringOneOrder($result, $tmpVal, $gender, $variants);
     //thousands
     list($result, $tmpVal) = $this->_sumStringOneOrder($result, $tmpVal, RUtils::FEMALE, array('тысяча', 'тысячи', 'тысяч'));
     //millions
     list($result, $tmpVal) = $this->_sumStringOneOrder($result, $tmpVal, RUtils::MALE, array('миллион', 'миллиона', 'миллионов'));
     //billions
     list($result, ) = $this->_sumStringOneOrder($result, $tmpVal, RUtils::MALE, array('миллиард', 'миллиарда', 'миллиардов'));
     return trim($result);
 }
Ejemplo n.º 30
0
 protected function cache(array $namesOrIds)
 {
     $ids = array();
     $names = array();
     foreach ($namesOrIds as $t) {
         $this->cache[$t] = 0;
         // prevent re-query
         if ($t == '*') {
             $lastTouchOnAnyTable = $this->connection->fetchAssoc('SELECT UNIX_TIMESTAMP(MAX(last_touched)) timestamp FROM wfd_meta');
             $this->cache['*'] = $lastTouchOnAnyTable['timestamp'];
         } elseif (is_numeric($t)) {
             $ids[] = $t;
         } else {
             $names[] = $t;
         }
     }
     if ($names || $ids) {
         $result = $this->connection->fetchAll('
             SELECT t.id, t.tablename, UNIX_TIMESTAMP(MAX(m.last_touched)) timestamp
             FROM wfd_meta m
             JOIN wfd_table t on m.wfd_table_id = t.id
             WHERE ' . ($ids ? 't.id IN (' . implode(', ', array_fill(0, count($ids), '?')) . ')' : '') . ($ids && $names ? ' OR ' : '') . ($names ? 't.tablename IN (' . implode(', ', array_fill(0, count($names), '?')) . ')' : '') . '
             GROUP BY t.id', array_merge($ids, $names));
         foreach ($result as $row) {
             $this->cache[$row['id']] = $this->cache[$row['tablename']] = $row['timestamp'];
         }
     }
 }