public function getInbox($page = 1, $perPage = 25, $sort = null) { if (!$this->isConnect) { return false; } $start = $page == 1 ? 0 : $page * $perPage - ($perPage - 1); $order = 0; $by = SORTDATE; if (is_array($sort)) { $order = $this->sortBy['order'][$sort[0]]; $by = $this->sortBy['by'][$sort[1]]; } $sorted = imap_sort($this->stream, $by, $order); $mails = array_chunk($sorted, $perPage); $mails = $mails[$page - 1]; $mbox = imap_check($this->stream); $inbox = imap_fetch_overview($this->stream, implode($mails, ','), 0); if (!is_array($inbox)) { return false; } if (is_array($inbox)) { $temp_inbox = []; foreach ($inbox as $msg) { $temp_inbox[$msg->msgno] = $msg; } foreach ($mails as $msgno) { $this->inbox[$msgno] = $temp_inbox[$msgno]; } } return $this->inbox; }
function convert_uudecode($string) { // Sanity check if (!is_scalar($string)) { user_error('convert_uuencode() expects parameter 1 to be string, ' . gettype($string) . ' given', E_USER_WARNING); return false; } if (strlen($string) < 8) { user_error('convert_uuencode() The given parameter is not a valid uuencoded string', E_USER_WARNING); return false; } $decoded = ''; foreach (explode("\n", $string) as $line) { $c = count($bytes = unpack('c*', substr(trim($line), 1))); while ($c % 4) { $bytes[++$c] = 0; } foreach (array_chunk($bytes, 4) as $b) { $b0 = $b[0] == 0x60 ? 0 : $b[0] - 0x20; $b1 = $b[1] == 0x60 ? 0 : $b[1] - 0x20; $b2 = $b[2] == 0x60 ? 0 : $b[2] - 0x20; $b3 = $b[3] == 0x60 ? 0 : $b[3] - 0x20; $b0 <<= 2; $b0 |= $b1 >> 4 & 0x3; $b1 <<= 4; $b1 |= $b2 >> 2 & 0xf; $b2 <<= 6; $b2 |= $b3 & 0x3f; $decoded .= pack('c*', $b0, $b1, $b2); } } return rtrim($decoded, ""); }
function test_identifier() { global $server; $server->child_single_work_item_set(true); $server->max_work_per_child_set(1); echo "Adding 100 units of work\n"; /* add work */ $data_set = array(); for ($i = 0; $i < 100; $i++) { $data_set[] = $i; } shuffle($data_set); $data_set = array_chunk($data_set, 3); $i = 0; foreach ($data_set as $item) { $server->addwork($item, "IDn{$i}"); $i++; } echo "Processing work in non-blocking mode\n"; /* process work non blocking mode */ $server->process_work(false); /* wait until all work allocated */ while ($server->work_sets_count() > 0) { echo "work set count: " . $server->work_sets_count() . "\n"; $server->process_work(false); sleep(1); } /* wait until all children finish */ while ($server->children_running() > 0) { echo "waiting for " . $server->children_running() . " children to finish\n"; sleep(1); } }
private function sendComponentRequests($component) { $items = Mage::getModel('M2ePro/StopQueue')->getCollection()->addFieldToFilter('is_processed', 0)->addFieldToFilter('component_mode', $component)->getItems(); $accountMarketplaceItems = array(); foreach ($items as $item) { /** @var Ess_M2ePro_Model_StopQueue $item */ $tempKey = (string) $item->getMarketplaceId() . '_' . $item->getAccountHash(); if (!isset($accountMarketplaceItems[$tempKey])) { $accountMarketplaceItems[$tempKey] = array(); } if (count($accountMarketplaceItems[$tempKey]) >= 100) { continue; } $accountMarketplaceItems[$tempKey][] = $item; } foreach ($accountMarketplaceItems as $items) { if ($component == Ess_M2ePro_Helper_Component_Ebay::NICK) { $parts = array_chunk($items, 10); foreach ($parts as $part) { if (count($part) <= 0) { continue; } $this->sendAccountMarketplaceRequests($component, $part); } } else { $this->sendAccountMarketplaceRequests($component, $items); } foreach ($items as $item) { /** @var Ess_M2ePro_Model_StopQueue $item */ $item->setData('is_processed', 1)->save(); } } return count($accountMarketplaceItems) > 0; }
function permute($key) { $res = array(); // support 3DES keys of 16 bytes if (($i = count($key)) > KEY_SIZE) { foreach (array_chunk($key, KEY_SIZE) as $subkey) { $res = array_merge($res, permute($subkey)); } return $res; } else { if ($i != KEY_SIZE) { exit("key size needs to be multiples of 8 bytes"); } } for ($i = 0; $i < KEY_SIZE; $i++) { $p = 0; $mask = 0x80 >> $i; foreach ($key as $byte) { $p >>= 1; if ($byte & $mask) { $p |= 0x80; } } $res[] = $p; } return $res; }
public function onRebuild(Am_Event $event) { $rows = $this->getDi()->db->select("SELECT u.login AS ARRAY_KEY, u.user_id, IFNULL(s.pass, ?) as pass\n FROM ?_user u LEFT JOIN ?_saved_pass s\n ON s.user_id=u.user_id AND s.format=?\n WHERE u.status = 1\n ", self::NO_PASSWORD, SavedPassTable::PASSWORD_CRYPT); $existing = array(); $f = fopen($this->htpasswd, 'r'); if ($f) { while ($s = fgets($f, 8192)) { @(list($l, $p) = explode(':', $s, 2)); $existing[trim($l)] = trim($p); } } // if (!flock($f, LOCK_EX)) { throw new Am_Exception_InternalError("Could not lock htpasswd file {$this->htpasswd} for updating"); } $fnName = $this->htpasswd . '.' . uniqid(); $fn = fopen($fnName, 'x'); if (!$fn) { throw new Am_Exception_InternalError("Could not open file {$fnName} for creation"); } foreach ($rows as $login => $r) { if ($r['pass'] == self::NO_PASSWORD && array_key_exists($login, $existing)) { $r['pass'] = $existing[$login]; } fwrite($fn, "{$login}:" . $r['pass'] . PHP_EOL); } flock($f, LOCK_UN); fclose($f); fclose($fn); if (!rename($fnName, $this->htpasswd)) { throw new Am_Exception_InternalError("Could not move {$fnName} to {$this->htpasswd}"); } /// rebuild .htaccess $groups = array(); $q = $this->getDi()->resourceAccessTable->getResourcesForMembers(ResourceAccess::FOLDER)->query(); $db = $this->getDi()->db; while ($r = $db->fetchRow($q)) { $groups[$r['resource_id']][] = $r['login']; } $f = fopen($this->htgroup, 'r'); if (!flock($f, LOCK_EX)) { throw new Am_Exception_InternalError("Could not lock htgroup file {$this->htgroup} for updating"); } $fnName = $this->htgroup . '.' . uniqid(); $fn = fopen($fnName, 'x'); if (!$fn) { throw new Am_Exception_InternalError("Could not open file {$fnName} for creation"); } foreach ($groups as $folder_id => $logins) { foreach (array_chunk($logins, 300) as $logins) { fputs($fn, "FOLDER_{$folder_id}: " . implode(" ", $logins) . PHP_EOL); } } flock($f, LOCK_UN); fclose($f); fclose($fn); if (!rename($fnName, $this->htgroup)) { throw new Am_Exception_InternalError("Could not move {$fnName} to {$this->htgroup}"); } }
protected function enqueue_all_ids_as_action($action_name, $table_name, $id_field, $where_sql, $max_items_to_enqueue, $state) { global $wpdb; if (!$where_sql) { $where_sql = '1 = 1'; } $items_per_page = 1000; $page = 1; $chunk_count = 0; $previous_max_id = $state ? $state : '~0'; $listener = Jetpack_Sync_Listener::get_instance(); // count down from max_id to min_id so we get newest posts/comments/etc first while ($ids = $wpdb->get_col("SELECT {$id_field} FROM {$table_name} WHERE {$where_sql} AND {$id_field} < {$previous_max_id} ORDER BY {$id_field} DESC LIMIT {$items_per_page}")) { // Request posts in groups of N for efficiency $chunked_ids = array_chunk($ids, self::ARRAY_CHUNK_SIZE); // if we hit our row limit, process and return if ($chunk_count + count($chunked_ids) >= $max_items_to_enqueue) { $remaining_items_count = $max_items_to_enqueue - $chunk_count; $remaining_items = array_slice($chunked_ids, 0, $remaining_items_count); $listener->bulk_enqueue_full_sync_actions($action_name, $remaining_items); $last_chunk = end($remaining_items); return array($remaining_items_count + $chunk_count, end($last_chunk)); } $listener->bulk_enqueue_full_sync_actions($action_name, $chunked_ids); $chunk_count += count($chunked_ids); $page += 1; $previous_max_id = end($ids); } return array($chunk_count, true); }
public function loadByUIDBatch($ids) { $db = FD::db(); $sql = $db->sql(); $streamIds = array(); foreach ($ids as $pid) { if (!isset(self::$_streamitems[$pid])) { $streamIds[] = $pid; } } if ($streamIds) { foreach ($streamIds as $pid) { self::$_streamitems[$pid] = false; } $idSegments = array_chunk($streamIds, 5); //$idSegments = array_chunk( $streamIds, count($streamIds) ); $query = ''; for ($i = 0; $i < count($idSegments); $i++) { $segment = $idSegments[$i]; $ids = implode(',', $segment); $query .= 'select * from `#__social_stream_item` where `uid` IN ( ' . $ids . ')'; if ($i + 1 < count($idSegments)) { $query .= ' UNION '; } } $sql->raw($query); $db->setQuery($sql); $results = $db->loadObjectList(); if ($results) { foreach ($results as $row) { self::$_streamitems[$row->uid] = $row; } } } }
public static function render_instance(BlockInstance $instance, $editing = false) { $configdata = $instance->get('configdata'); if (!empty($configdata['feedid'])) { $data = get_record('blocktype_externalfeed_data', 'id', $configdata['feedid'], null, null, null, null, 'id,url,link,title,description,content,' . db_format_tsfield('lastupdate') . ',image'); $data->content = unserialize($data->content); $data->image = unserialize($data->image); // only keep the number of entries the user asked for $chunks = array_chunk($data->content, isset($configdata['count']) ? $configdata['count'] : 10); $data->content = $chunks[0]; // Attempt to fix relative URLs in the feeds if (!empty($data->image['link'])) { $data->description = preg_replace('/src="(\\/[^"]+)"/', 'src="' . $data->image['link'] . '$1"', $data->description); foreach ($data->content as &$entry) { $entry->description = preg_replace('/src="(\\/[^"]+)"/', 'src="' . $data->image['link'] . '$1"', $entry->description); } } $smarty = smarty_core(); $smarty->assign('title', $data->title); $smarty->assign('description', $data->description); $smarty->assign('url', $data->url); // 'full' won't be set for feeds created before 'full' support was added $smarty->assign('full', isset($configdata['full']) ? $configdata['full'] : false); $smarty->assign('link', $data->link); $smarty->assign('entries', $data->content); $smarty->assign('feedimage', self::make_feed_image_tag($data->image)); $smarty->assign('lastupdated', get_string('lastupdatedon', 'blocktype.externalfeed', format_date($data->lastupdate))); return $smarty->fetch('blocktype:externalfeed:feed.tpl'); } return ''; }
/** * Send email notifications for a post. * * Sends up to emails_per_chunk unsent notifications, and schedules another chunk if there are more. */ public function send() { $recipient_values = $this->batch->add_unsent_recipients()->get_individual_message_values(); $chunks = array_chunk($recipient_values, absint(Prompt_Core::$options->get('emails_per_chunk'))); if (empty($chunks[0])) { return null; } $chunk = $chunks[0]; /** * Filter whether to send new post notifications. Default true. * * @param boolean $send Whether to send notifications. * @param WP_Post $post * @param array $recipient_ids */ if (!apply_filters('prompt/send_post_notifications', true, $this->batch->get_context()->get_post(), $chunk)) { return null; } $this->batch->set_individual_message_values($chunk)->lock_for_sending(); $result = parent::send(); if (!$this->rescheduled and !empty($chunks[1])) { $this->schedule_next_chunk(); } return $result; }
/** * load the user contacts */ function getUserContacts() { $parameters = array('cursor' => '-1'); $response = $this->api->get('friends/ids.json', $parameters); // check the last HTTP status code returned if ($this->api->http_code != 200) { throw new Exception("User contacts request failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus($this->api->http_code)); } if (!$response || !count($response->ids)) { return array(); } // 75 id per time should be okey $contactsids = array_chunk($response->ids, 75); $contacts = array(); foreach ($contactsids as $chunk) { $parameters = array('user_id' => implode(",", $chunk)); $response = $this->api->get('users/lookup.json', $parameters); // check the last HTTP status code returned if ($this->api->http_code != 200) { throw new Exception("User contacts request failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus($this->api->http_code)); } if ($response && count($response)) { foreach ($response as $item) { $uc = new Hybrid_User_Contact(); $uc->identifier = property_exists($item, 'id') ? $item->id : ""; $uc->displayName = property_exists($item, 'name') ? $item->name : ""; $uc->profileURL = property_exists($item, 'screen_name') ? $item->screen_name : ""; $uc->photoURL = property_exists($item, 'profile_image_url') ? $item->profile_image_url : ""; $uc->description = property_exists($item, 'description') ? $item->description : ""; $contacts[] = $uc; } } } return $contacts; }
public static function articleNum($massive, $in, $get) { // Основной блок, содержащий дополнительные блоки (по сути двумерный массив) $mainBlock = array(); $massi = array_chunk($massive, $in); $inBlock = 0; // Смещаю отсчет массива с 0 на ед-цу for ($k = 0; $k < count($massi); $k++) { $y[$k + 1] = $massi[$k]; } // Цикл по внешнему массиву (по количеству внеутренних массивов) for ($j = 1; $j <= count($y); $j++) { $inBlock = count($y[$j]); // Создаем разделитель-блоков (т.е., начиная с которого, отсчитывается очередной внутренний блок (= массив)) $from = $inBlock * ($get - 1); // Цикл по внутреннему массиву (по количеству элементов внеутренних массивов) for ($i = $from; $i < $from + $inBlock; $i++) { // !!! Добавление собачки @ - вынужденная мера! Без нее выскакивает замечание (Notice) (при включенном error_reporting(E_ALL);), // -- Notice: Undefined offset: 54 in Z:\home\site\www\libs\pages.php on line 61 // из-за того, что $inBlock может меняться в течении выполнения ф-ии @($mainBlock[$j][] = $massive[$i]); } } // Возвращаем основной Блок return $mainBlock; }
/** * @see AM_Task_Worker_Abstract::_fire() * @throws AM_Task_Worker_Exception * @return void */ protected function _fire() { $iIssueId = intval($this->getOption('issue_id')); $sMessage = $this->getOption('message'); $iBadge = intval($this->getOption('badge')); $oIssue = AM_Model_Db_Table_Abstract::factory('issue')->findOneBy('id', $iIssueId); /* @var $oIssue AM_Model_Db_Issue */ if (is_null($oIssue)) { throw new AM_Task_Worker_Exception('Issue not found'); } $iApplicationId = $oIssue->getApplication()->id; if (empty($iApplicationId)) { throw new AM_Task_Worker_Exception('Wrong parameters were given'); } $oTokensRow = AM_Model_Db_Table_Abstract::factory('device_token')->getTokens($iApplicationId, AM_Model_Pns_Type::PLATFORM_IOS); if (0 === $oTokensRow->count()) { $this->finish(); $this->getLogger()->debug('There are not tokens to notificate'); return; } $aSenderTaskOptions = array('message' => $sMessage, 'badge' => $iBadge, 'application_id' => $iApplicationId); $aTokensGroups = array_chunk($oTokensRow->toArray(), 100); foreach ($aTokensGroups as $aTokensGroup) { $aTokens = array(); foreach ($aTokensGroup as $aToken) { $this->getLogger()->debug(sprintf('Preparing message for token apple \'%s\'', $aToken["token"])); $aTokens[] = $aToken['token']; } $aSenderTaskOptions['tokens'] = $aTokens; $oTaskSender = new AM_Task_Worker_Notification_Sender_Apple(); $oTaskSender->setOptions($aSenderTaskOptions); $oTaskSender->create(); } }
function get_recent_post_titles($howmany) { $entryDir = opendir("blogs/"); $titles = array(); while (false !== ($file = readdir($entryDir))) { $lastname = substr(strrchr($file, "."), 1); if ($lastname == "blog" && $lastname != "php" && $file != "." && $file != "..") { $entrys[filemtime("blogs/{$file}")] = $file; } } krsort($entrys); /* use only as many as requested. */ $chunked_entries = array_chunk($entrys, $howmany, TRUE); $entries = $chunked_entries[0]; $retval = ""; foreach ($entrys as $creation => $entry) { $pattern = "/<h1 ?.*>(.*)<\\/h1>/"; $post = file_get_contents("blogs/{$entry}"); preg_match($pattern, $post, $matches); $title = $matches[0]; $body = str_replace($title, '', $post); $body = substr(strip_tags($body), 0, $summary_length); $title = strip_tags($title); $site = "http://" . $_SERVER['SERVER_NAME'] . dirname($_SERVER['REQUEST_URI']) . '/blog.php'; $retval .= "<li><a class=\"link\" href=\"{$site}?{$entry}\">{$title}</a></li>\n"; } return $retval; }
public function getGeneralFromAttributeSets(array $attributeSets) { $attributeSetIds = $this->_getIdsFromInput($attributeSets, 'attribute_set_id'); if (empty($attributeSetIds)) { return array(); } $attributes = array(); $isFirst = true; $idsParts = array_chunk($attributeSetIds, 50); foreach ($idsParts as $part) { $tempAttributes = $this->_getGeneralFromAttributeSets($part); if ($isFirst) { $attributes = $tempAttributes; $isFirst = false; continue; } if (!$isFirst && empty($attributes)) { return array(); } $attributes = array_intersect($attributes, $tempAttributes); } if (empty($attributes)) { return array(); } $attributesData = Mage::getResourceModel('catalog/product_attribute_collection')->addVisibleFilter()->addFieldToFilter('main_table.attribute_id', array('in' => $attributes))->setOrder('frontend_label', Varien_Data_Collection_Db::SORT_ORDER_ASC)->toArray(); $resultAttributes = array(); foreach ($attributesData['items'] as $attribute) { $resultAttributes[] = array('code' => $attribute['attribute_code'], 'label' => $attribute['frontend_label']); } return $resultAttributes; }
function api_data_source_remove_multi($local_data_ids) { // Shortcut out if no data if (!sizeof($local_data_ids)) { return; } $local_data_ids_chunks = array_chunk($local_data_ids, 1000); foreach ($local_data_ids_chunks as $ids_to_delete) { $data_template_data_ids = db_fetch_assoc("SELECT id\n\t\t\t\t\tFROM data_template_data\n\t\t\t\t\tWHERE local_data_id IN (" . implode(',', $ids_to_delete) . ")"); if (sizeof($data_template_data_ids)) { $dtd_ids_to_delete = array(); foreach ($data_template_data_ids as $data_template_data_id) { $dtd_ids_to_delete[] = $data_template_data_id["id"]; if (sizeof($dtd_ids_to_delete) >= 1000) { db_execute("DELETE FROM data_template_data_rra WHERE data_template_data_id IN (" . implode(",", $dtd_ids_to_delete) . ")"); db_execute("DELETE FROM data_input_data WHERE data_template_data_id IN (" . implode(",", $dtd_ids_to_delete) . ")"); $dtd_ids_to_delete = array(); } } if (sizeof($dtd_ids_to_delete)) { db_execute("DELETE FROM data_template_data_rra WHERE data_template_data_id IN (" . implode(",", $dtd_ids_to_delete) . ")"); db_execute("DELETE FROM data_input_data WHERE data_template_data_id IN (" . implode(",", $dtd_ids_to_delete) . ")"); } } db_execute("DELETE FROM data_template_data WHERE local_data_id IN (" . implode(",", $ids_to_delete) . ")"); db_execute("DELETE FROM data_template_rrd WHERE local_data_id IN (" . implode(",", $ids_to_delete) . ")"); db_execute("DELETE FROM poller_item WHERE local_data_id IN (" . implode(",", $ids_to_delete) . ")"); db_execute("DELETE FROM data_local WHERE id IN (" . implode(",", $ids_to_delete) . ")"); } }
/** * import function. * * @access public * @param array $array * @param array $columns * @return void */ function import($array = array(), $columns = array('post_title')) { $this->imported = $this->skipped = 0; if (!is_array($array) || !sizeof($array)) { $this->footer(); die; } $rows = array_chunk($array, sizeof($columns)); foreach ($rows as $row) { $row = array_filter($row); if (empty($row)) { continue; } $meta = array(); foreach ($columns as $index => $key) { $meta[$key] = sp_array_value($row, $index); } $name = sp_array_value($meta, 'post_title'); if (!$name) { $this->skipped++; continue; } $args = array('post_type' => 'sp_sponsor', 'post_status' => 'publish', 'post_title' => $name); $id = wp_insert_post($args); // Update URL update_post_meta($id, 'sp_url', sp_array_value($meta, 'sp_url')); $this->imported++; } // Show Result echo '<div class="updated settings-error below-h2"><p> ' . sprintf(__('Import complete - imported <strong>%s</strong> sponsors and skipped <strong>%s</strong>.', 'prosports'), $this->imported, $this->skipped) . ' </p></div>'; $this->import_end(); }
private function insertChanges() { if (count($this->changes) <= 0) { $this->log('The updated products are not presented in the M2e Pro Listings.'); return; } $tableName = $this->tablename('m2epro_product_change'); $existedChanges = array(); foreach (array_chunk($this->changes, 500, true) as $productChangesPart) { if (count($productChangesPart) <= 0) { continue; } $stmt = $this->select("SELECT *\n FROM `{$tableName}`\n WHERE `product_id` IN (?)", implode(',', array_keys($productChangesPart))); while ($row = $stmt->fetch()) { $existedChanges[] = $row['product_id'] . '##' . $row['attribute']; } } $insertSql = "INSERT INTO `{$tableName}`\n (`product_id`,`action`,`attribute`,`initiators`,`update_date`,`create_date`)\n VALUES (?,?,?,?,?,?)"; foreach ($this->changes as $productId => $change) { if (in_array($change['product_id'] . '##' . $change['attribute'], $existedChanges)) { $this->statistics['existed']++; continue; } $this->statistics['inserted']++; $this->insert($insertSql, array($change['product_id'], $change['action'], $change['attribute'], $change['initiators'], $change['update_date'], $change['create_date'])); } $this->saveStatistics(); }
public function getLatestMails($o) { $aResults = array(); $aRes = $this->imapProxy->getMMGMaxInFolder($this->imapProxy->currentFolder64, $this->imapProxy->currentFolderStatus['uidvalidity']); $sMinDate = $aRes[0]['max_date'] == '' ? '1980-01-01' : $aRes[0]['max_date']; //$iMinId = max(1,O + $aRes[0]['max_id']); $oUnseenQuery = new Horde_Imap_Client_Search_Query(array('peek' => true)); $oUnseenQuery->flag('SEEN', false); $oUnseenQuery->dateSearch($sMinDate, Horde_Imap_Client_Search_Query::DATE_SINCE); $results = $this->imapProxy->search($oUnseenQuery); $aAllIDs = $results['match']->ids; if (count($aAllIDs)) { $aChunksID = array_chunk($aAllIDs, 30); foreach ($aChunksID as $aMsg) { $oMMG = new MMG_MAIL_MESSAGE(); $aMMG = $oMMG->get(array('cols' => array('group_concat(MMG_UID order by MMG_UID) as UIDS'), 'where' => array('MMG_FOLDER' => $this->imapProxy->currentFolder64, 'MMG_FOLDER_UUID' => $this->imapProxy->currentFolderStatus['uidvalidity'], 'MMG_UID' => array('IN', $aMsg)))); $aMMGId = explode(',', $aMMG[0]['uids']); $aMsgToDo = array_diff($aMsg, $aMMGId); $aTmp = $this->imapProxy->fetch_overviewWithCache($aMsgToDo, array('account' => $o['account'], 'folder' => $this->imapProxy->currentFolder64)); foreach ($aTmp as $aHeader) { $from = $aHeader->from[0]->name ? $aHeader->from[0]->name : $aHeader->from[0]->email; if (!array_key_exists($from, $aResults)) { $aResults[$from] = array(); } $aResults[$from][] = $aHeader->subject; } } if (count($aResults) > 0) { $this->stomp->send("/topic/imapNotifierOnMessage/" . $o['account'], json_encode(array('newEmails' => $aResults))); } } }
protected function updateIndex($entities, $method) { if (null === $this->documentEndpoint) { return true; } $data = array(); if (!is_array($entities)) { $entities = array($entities); } foreach ($entities as $entity) { if ($entity instanceof IndexableEntityInterface) { $data[] = $this->prepareIndexData($entity->toSearchArray(), $method); } elseif (is_array($entity)) { $data[] = $this->prepareIndexData($entity, $method); } else { throw new Exception\RuntimeException('Invalid entity provided for indexing'); } } $count = 0; foreach (array_chunk($data, 5000) as $chunk) { $result = $this->index($chunk); if (!$result) { $count = 0; break; } $count = $count + $result; } return $count; }
/** * @param \Illuminate\Http\Request $request * * @return \Illuminate\Http\JsonResponse */ public function resolveIdsToNames(Request $request) { $ids = array_unique(explode(',', $request->ids)); // Init the initial return array $response = []; // Populate any entries from the cache foreach ($ids as $id) { if (Cache::has($this->prefix . $id)) { $response[$id] = Cache::get($this->prefix . $id); unset($ids[$id]); } } // Call the EVE API for any outstanding ids that need // resolution if (!empty($ids)) { $pheal = app()->make('Seat\\Eveapi\\Helpers\\PhealSetup')->getPheal(); foreach (array_chunk($ids, 30) as $id_chunk) { $names = $pheal->eveScope->CharacterName(['ids' => implode(',', $id_chunk)]); foreach ($names->characters as $result) { Cache::forever($this->prefix . $result->characterID, $result->name); $response[$result->characterID] = $result->name; } } } return response()->json($response); }
/** * index method * * @return void */ public function index() { $galleryCategories = $this->_getCategory(); if (isset($this->request->query['id'])) { $gallery = $this->view($this->request->query['id']); $gallery_category_id = $gallery['Gallery']['gallery_category_id']; } else { if (isset($this->request->query['gallery_category_id'])) { if ($this->GalleryCategories->exists($this->request->query['gallery_category_id'])) { $gallery_category_id = $this->request->query['gallery_category_id']; } else { throw new NotFoundException(__('Invalid post')); } } else { $gallery_category_id = key($galleryCategories->toArray()); } $gallery = $this->Galleries->find('All', array('conditions' => array('gallery_category_id' => $gallery_category_id)))->First(); } $this->Galleries->recursive = 0; $this->paginate = array('conditions' => array('gallery_category_id' => $gallery_category_id)); if (count($gallery)) { $this->set('gallery', $gallery); } $galleries = $this->paginate($this->Galleries)->toArray(); $this->set('galleries', array_chunk($galleries, 6)); $this->set('galleryCategoryId', $gallery_category_id); }
function utf8_str_split($str = '', $len = 1) { preg_match_all("/./u", $str, $arr); $arr = array_chunk($arr[0], $len); $arr = array_map('implode', $arr); return $arr; }
public function process($relex, $preview = false) { $relexLines = $this->array_unique_multidimensional(explode("\n", $relex['content'])); $relex['content'] = null; if ($preview) { $relexLines = array_slice($relexLines, 0, 100); return $this->processLines($relexLines); } if (count($relexLines) > 10000) { $arrayChunks = array_chunk($relexLines, 10000); } else { $arrayChunks = array($relexLines); } unset($relexLines); $this->createSoftwareAgent(); $this->createActivity(); $inc = $this->getLastDocumentInc(); foreach ($arrayChunks as &$chunkVal) { try { $inc = $this->store($relex, $this->processLines($chunkVal), $inc); } catch (Exception $e) { $this->status['store'] = $e->getMessage(); $this->activity->forceDelete(); } } return $this->status; }
public function index() { $dirs = glob(APP_PATH . C("APP_GROUP_PATH") . DIRECTORY_SEPARATOR . '*'); foreach ($dirs as $path) { if (is_dir($path)) { $path = basename($path); $dirs_arr[] = $path; } } //数量 $total = count($dirs_arr); //把一个数组分割为新的数组块 $dirs_arr = array_chunk($dirs_arr, 20, true); //当前分页 $page = max(intval($_GET['page']), 1); $directory = $dirs_arr[intval($page - 1)]; $pages = $this->page($total, 20); $modulesdata = M("Module")->select(); foreach ($modulesdata as $v) { $modules[$v['module']] = $v; } $this->assign("Page", $pages->show("Admin")); $this->assign("data", $directory); $this->assign("modules", $modules); $this->display(); }
function getModbusRegisters($modbusHostname, $slaveAddress, $startRegister, $nRegisters) { /* printf("# getModbusRegisters(modbusHostname=%s, slaveAddress=%s, startRegister=%s, nRegisters=%s\n", $modbusHostname, $slaveAddress, $startRegister, $nRegisters ); */ $modbus = new ModbusMaster($modbusHostname, "TCP"); /* read registers */ try { $result = $modbus->readMultipleRegisters($slaveAddress, $startRegister, $nRegisters); } catch (Exception $e) { printf("Exception: %s\n", $e); return array(); } /* split into 1 word (2 byte) chunks */ $result = array_chunk($result, 2); /* word results */ $r = array(); for ($i = 0; $i < sizeof($result); $i++) { $r[$i + $startRegister] = PhpType::bytes2unsignedInt($result[$i]); } return $r; }
function convert_uuencode($string) { // Sanity check if (!is_scalar($string)) { user_error('convert_uuencode() expects parameter 1 to be string, ' . gettype($string) . ' given', E_USER_WARNING); return false; } $u = 0; $encoded = ''; while ($c = count($bytes = unpack('c*', substr($string, $u, 45)))) { $u += 45; $encoded .= pack('c', $c + 0x20); while ($c % 3) { $bytes[++$c] = 0; } foreach (array_chunk($bytes, 3) as $b) { $b0 = ($b[0] & 0xfc) >> 2; $b1 = (($b[0] & 0x3) << 4) + (($b[1] & 0xf0) >> 4); $b2 = (($b[1] & 0xf) << 2) + (($b[2] & 0xc0) >> 6); $b3 = $b[2] & 0x3f; $b0 = $b0 ? $b0 + 0x20 : 0x60; $b1 = $b1 ? $b1 + 0x20 : 0x60; $b2 = $b2 ? $b2 + 0x20 : 0x60; $b3 = $b3 ? $b3 + 0x20 : 0x60; $encoded .= pack('c*', $b0, $b1, $b2, $b3); } $encoded .= "\n"; } // Add termination characters $encoded .= "`\n"; return $encoded; }
function pageNavi() { $url = ACTUAL_URL; $current = $this->page; $stack = $this->total; for ($i = 1; $i <= $stack; $i++) { $stack_temp[$i] = $i; } $stack = array_chunk($stack_temp, 5, true); $out[] = '<nav><ul class="pagination">'; for ($i = 0; $i <= count($stack); $i++) { if (in_array($current, $stack[$i])) { if ($i > 0) { $out[] = '<li><a href="' . $url . '/page/' . ($current - 1) . '" class="page-numbers">«</a></li>'; } foreach ($stack[$i] as $raw) { if ($raw == $current) { $out[] = '<li class="active"><span class="page-numbers current">' . $raw . '</span></li>'; } else { $out[] = '<li><a href="' . $url . '/page/' . $raw . '" class="page-numbers">' . $raw . '</a></li>'; } } if ($current < $this->total) { $out[] = '<li><a href="' . $url . '/page/' . ($current + 1) . '" class="page-numbers">»</a></li>'; } break 1; } } $out[] = '</ul></nav>'; return implode('', $out); }
/** * Run the Update * * @return mixed|void */ public function call() { $pheal = $this->setScope('char')->getPheal(); foreach ($this->api_info->characters as $character) { // Get a list of messageIDs that we do not have mail // bodies for. These ID's will be used to try and // pull the bodies using this api key $message_ids = DB::table('character_mail_messages')->where('characterID', $character->characterID)->whereNotIn('messageID', function ($query) { $query->select('messageID')->from('character_mail_message_bodies'); })->lists('messageID'); // It is possible to provide a comma seperated list // of messageIDs to the MailBodies endpoint. Pheal // caches XML's on disk by file name. To prevent file // names from becoming too long, we will chunk the // ids we want to update. foreach (array_chunk($message_ids, 10) as $message_id_chunk) { $result = $pheal->MailBodies(['characterID' => $character->characterID, 'ids' => implode(',', $message_id_chunk)]); foreach ($result->messages as $body) { MailMessageBody::create(['messageID' => $body->messageID, 'body' => $body->__toString()]); } } // Foreach messageID chunk } return; }
/** * Splits $expressionList into multiple chunks. * * @param array $expressionList * @param bool $preserveArrayKeys If TRUE, array keys are preserved in array_chunk() * @return array */ public function splitMaxExpressions($expressionList, $preserveArrayKeys = FALSE) { if (!$this->specificExists(self::LIST_MAXEXPRESSIONS)) { return array($expressionList); } return array_chunk($expressionList, $this->getSpecific(self::LIST_MAXEXPRESSIONS), $preserveArrayKeys); }